iOS - 使用自动布局设置 UILabel 的最大宽度

标签 ios uiview autolayout uilabel

我有一个 UILabel 包含在一个具有固定大小的 UIView 中。 UILabel 具有动态文本。我如何确保 UILabel 永远不会比包含它的 UIView 大?

在使用 AutoLayout 之前,这很简单,只需使用 AdjustsFontSizeToFitWidth 即可实现,但我无法再使用 Autolayout 来实现这一点。

我应该从 UILabel 添加什么约束到 UIView?现在它只是领先对齐。

最佳答案

UILabel(contentHuggingcontentCompressionResistance)这样的 View 有特殊的方法,但它们已经启用。所以你只需要禁用标签的宽度增长到 super View 的宽度。

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];

关于iOS - 使用自动布局设置 UILabel 的最大宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34088683/

相关文章:

ios - 如何从 NSLayoutConstraints 获取 CGFloat 值?

ios - 在导航 Controller 中的导航栏下方添加 View

ios - 如何让 UITableView 在动态高度单元格中滚动到底部?

iphone - iOS:如何响应物理键盘的上/下/左/右箭头事件?

objective-c - 没有隐藏项目的 Core Graphics 屏幕截图

ios - *完全复制 UIView*

ios - 使用 .xib 的 UIScrollView 自动布局

ios - KineticJS 在 iPad 2 上非常慢

iphone - UITextField - 在输入第一个字符后添加一个字符

Swift - UIView 何时更新其框架?