iOS - 使用自动布局设置 UILabel 的最大宽度
iOS - set maximum width for UILabel with Autolayout
我有一个 UILabel
包含在具有固定大小的 UIView
中。 UILabel
有动态文本。我怎样才能确保 UILabel
永远不会比包含的 UIView 更大?
在使用 AutoLayout
之前,这很简单,只需使用 AdjustsFontSizeToFitWidth
即可实现,但我无法再使用 Autolayout 来实现它。
我应该从 UILabel
到 UIView
添加什么约束?现在它只是前导对齐。
像 UILabel
(contentHugging
和 contentCompressionResistance
)这样的视图有特殊的方法,但它们已经启用。所以你需要禁用标签的宽度增长到超级视图的宽度。
NSLayoutConstraint *widthConstraint = [NSLayoutConstraint constraintWithItem:self.label attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationLessThanOrEqual toItem:self.label.superview attribute:NSLayoutAttributeWidth multiplier:1.0f constant:0.0f];
[self.label addConstraint:widthConstraint];
我将添加左、上、右约束,如下所示:
在故事板中,只需点击几下:
- Select 你的标签
- 在添加约束面板(右下角)中,select 您要添加的约束
拖动标签并调整其大小以适合整个屏幕宽度,可能会在两边留一些边距。
设置 4 个约束:
1)标签的高度。
2) 置顶 space 到 UIView。
3) 引导 space 到 UIView。
4) 尾随 space 到 UIView.
最后将Label的horizontalcompressionResistense优先级设为1000
Swift 3 和 4
var widthConstraint = NSLayoutConstraint(item: label, attribute: .width, relatedBy: .lessThanOrEqual, toItem: label.superview, attribute: .width, multiplier: 1.0, constant: 0.0)
label.addConstraint(widthConstraint)
我有一个 UILabel
包含在具有固定大小的 UIView
中。 UILabel
有动态文本。我怎样才能确保 UILabel
永远不会比包含的 UIView 更大?
在使用 AutoLayout
之前,这很简单,只需使用 AdjustsFontSizeToFitWidth
即可实现,但我无法再使用 Autolayout 来实现它。
我应该从 UILabel
到 UIView
添加什么约束?现在它只是前导对齐。
像 UILabel
(contentHugging
和 contentCompressionResistance
)这样的视图有特殊的方法,但它们已经启用。所以你需要禁用标签的宽度增长到超级视图的宽度。
NSLayoutConstraint *widthConstraint = [NSLayoutConstraint constraintWithItem:self.label attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationLessThanOrEqual toItem:self.label.superview attribute:NSLayoutAttributeWidth multiplier:1.0f constant:0.0f];
[self.label addConstraint:widthConstraint];
我将添加左、上、右约束,如下所示:
在故事板中,只需点击几下:
- Select 你的标签
- 在添加约束面板(右下角)中,select 您要添加的约束
拖动标签并调整其大小以适合整个屏幕宽度,可能会在两边留一些边距。 设置 4 个约束: 1)标签的高度。 2) 置顶 space 到 UIView。 3) 引导 space 到 UIView。 4) 尾随 space 到 UIView.
最后将Label的horizontalcompressionResistense优先级设为1000
Swift 3 和 4
var widthConstraint = NSLayoutConstraint(item: label, attribute: .width, relatedBy: .lessThanOrEqual, toItem: label.superview, attribute: .width, multiplier: 1.0, constant: 0.0)
label.addConstraint(widthConstraint)