iOS - 使用Autolayout为UILabel设置最大宽度

el-*_*lor 7 uiview uilabel ios autolayout

我有一个UILabel包含在UIView固定大小的内容.在UILabel具有动态文本.我怎样才能确保UILabel永远不会比包含UIView更大?

在使用之前AutoLayout,通过简单地使用AdjustsFontSizeToFitWidth它就可以很容易地实现,但我无法再使用Autolayout了.

我应该从增加什么约束上UILabelUIView?现在它只是领先对齐.

Tim*_*ich 5

对于此类视图,有一些特殊的方法,例如UILabelcontentHuggingcontentCompressionResistance),但它们已经启用。因此,您需要禁用标签宽度的所有内容都将增长到超级视图的宽度。

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];
Run Code Online (Sandbox Code Playgroud)