ios - UILabel sizeToFit 不适用于自动布局 ios6

标签 ios ios6 uilabel autolayout

我应该如何以编程方式(以及使用哪种方法)配置高度取决于其文本的 UILabel?我一直在尝试结合使用 Storyboard 和代码来设置它,但无济于事。大家推荐在设置lineBreakModenumberOfLines的同时使用sizeToFit。但是,无论我将该代码放在 viewDidLoad:viewDidAppear: 还是 viewDidLayoutSubviews 中,我都无法让它工作。要么我把盒子做得太小而无法容纳长文本并且它不会变大,要么我把它做得太大而且它不会缩小。

最佳答案

请注意,在大多数情况下 Matt's solution按预期工作。但如果它对您不起作用,请进一步阅读。

要使您的标签自动调整高度,您需要执行以下操作:

  1. 设置标签的布局约束
  2. 设置低优先级的高度限制。它应该低于 ContentCompressionResistancePriority
  3. 设置 numberOfLines = 0
  4. 将 ContentHuggingPriority 设置为高于标签的高度优先级
  5. 为标签设置 preferredMaxLayoutWidth。标签使用该值来计算其高度

例如:

self.descriptionLabel = [[UILabel alloc] init];
self.descriptionLabel.numberOfLines = 0;
self.descriptionLabel.lineBreakMode = NSLineBreakByWordWrapping;
self.descriptionLabel.preferredMaxLayoutWidth = 200;

[self.descriptionLabel setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];
[self.descriptionLabel setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];
[self.descriptionLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
[self addSubview:self.descriptionLabel];

NSArray* constrs = [NSLayoutConstraint constraintsWithVisualFormat:@"|-8-[descriptionLabel_]-8-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(descriptionLabel_)];
[self addConstraints:constrs];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-8-[descriptionLabel_]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(descriptionLabel_)]];
[self.descriptionLabel addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[descriptionLabel_(220@300)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(descriptionLabel_)]];

使用界面生成器

  1. 设置四个约束。高度限制是强制性的。 enter image description here

  2. 然后转到标签的属性检查器并将行数设置为 0。 enter image description here

  3. 转到标签的尺寸检查器并增加垂直 ContentHuggingPriority 和垂直 ContentCompressionResistancePriority。
    enter image description here

  4. 选择并编辑高度限制。
    enter image description here

  5. 并降低高度约束优先级。
    enter image description here

尽情享受吧。 :)

关于ios - UILabel sizeToFit 不适用于自动布局 ios6,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16009405/

相关文章:

ios - 如何使用自动布局设置 ScrollView 内容大小?

iphone - 从 rtsp 链接 +iphone 播放视频

iphone - 直接从 Assets URL 读取

ios - 将Title设置为按钮并在单击两次时再次返回第一个标题

ios - 根据选定的 TableView 行更新 UILabel

ios - 在 Swift 中,如何获取 UILabel 文本基线的 y 位置?

iphone - 选择单元格时如何设置 accessoryType

ios - 在 iPhone 应用程序中存储 "total number of time spent"的值

iphone - iOS6 中的 UIImagePickerController 问题

uitableview - 在 UIAutomation 的自定义表部分标题 View 上设置accessibilityIdentifier