Swift – 调整fontSize以适应布局的宽度(以编程方式)
我一直在寻找一些dynamic调整我的fontSize
以适应我的布局框的宽度。 但是我能find的所有答案都是使用这个:
label.adjustsFontSizeToFitWidth = true
哪个工作。 但只有当我没有setTranslatesAutoresizingMaskIntoConstraints
设置为false
。
请注意,我不使用故事板。 所以要完全控制我的其他限制,我需要这一行:
label.setTranslatesAutoresizingMaskIntoConstraints(false)
所以我怎样才能调整字体大小,以适应宽度,而不使用故事板,当我不能使用adjustsFontSizeToFitWidth
。
在我弄清楚如何调整字体大小来适应宽度。 我还需要调整布局框的高度以适应字体大小。 虽然似乎有文件,但如果你碰巧也知道这个答案,这将不胜感激。
提前致谢
为您的标签尝试以下命令:
label.adjustsFontSizeToFitWidth = true label.minimumScaleFactor = 0.2
并尝试将标签的行更改为0和1(检查两种情况):
label.numberOfLines = 0 // or 1
我认为这会帮助你
目标C
[lb setMinimumScaleFactor:10.0/[UIFont labelFontSize]]; lb.adjustsFontSizeToFitWidth = YES;
Swift 3.0
lb.minimumScaleFactor = 10/UIFont.labelFontSize lb.adjustsFontSizeToFitWidth = true
我只是做了你需要的,完美的作品! (仅以编程方式) – 我们正在为标签设置较大的字体大小,以便将其重新缩放至完美的字体大小。
self.label.font = UIFont(name: "Heiti TC", size: 60) self.label.numberOfLines = 0 self.label.minimumScaleFactor = 0.1 self.label.baselineAdjustment = .alignCenters self.label.textAlignment = .center
如果您使用的是AutoLayout,请在viewDidLayoutSubviews
(布局布局之后)中实现此代码。
你的Roi
我不知道这是否会完全回答你的问题,但你可以使用这个扩展来计算自己的字体大小。
extension String { func height(constrainedBy width: CGFloat, with font: UIFont) -> CGFloat { let constraintSize = CGSize(width: width, height: .max) let boundingBox = self.boundingRectWithSize(constraintSize, options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil) return boundingBox.height } func width(constrainedBy height: CGFloat, with font: UIFont) -> CGFloat { let constrainedSize = CGSize(width: .max, height: height) let boundingBox = self.boundingRectWithSize(constrainedSize, options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil) return boundingBox.width } }
这是一个黑客解决scheme:
var size: CGFloat = 20 while titleLabel.frame.width > containerView.frame.width { titleLabel.font = UIFont.systemFont(ofSize: size) titleLabel.sizeToFit() size -= 1 }