如果UILabel的高度取决于其文本,我应该如何以编程方式(以及使用哪种方法)配置该UILabel呢?我一直试图使用故事板和代码的组合来设置它,但无济于事.在设置lineBreakModenumberOfLines时,每个人都推荐sizeToFit.但是,无论我把代码放在viewDidLoad:viewDidAppear:viewDidLayoutSubviews中,我都不能让它工作.要么我把框做得太小,不能容纳长文本,要么把它做得太大,不会缩小.

推荐答案

Please note在大多数情况下,Matt's solution的效果与预期相符.但如果这对你不起作用,请进一步阅读.

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

  1. 设置标签的布局约束
  2. 将高度约束设置为低优先级.它应该低于ContentCompressionResistancePriority
  3. 设置行数=0
  4. 将ContentHuggingPriority设置为高于标签的高度优先级
  5. 为标签设置首选项MaxLayoutWidth.标签使用该值来计算其高度

例如:

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

Using Interface Builder

  1. 设置四个约束条件.高度约束是强制性的.

  2. 然后转到标签的属性判断器并将行数设置为0. 在此处输入图像描述

  3. Go to the label's size inspector and increase vertical ContentHuggingPriority and vertical ContentCompressionResistancePriority.
    enter image description here

  4. Select and edit height constraint.
    enter image description here

  5. And decrease height constraint priority.
    enter image description here

Enjoy. :)

Ios相关问答推荐

通过在SWIFT中不起作用的泛型传递协议一致性类型

在iOS 17脉冲符号效果不起作用的情况下制作UIBarButtonItem动画(没有UIImageView)

为什么下面的代码没有在主线程上运行?

iOS Swift 应用程序实例的存活时间

不使用故事板创建 iMessage 应用程序

uikit中如何触发swiftui功能

更新 flutter 和 xcode 后 Xcode 14.3 中缺少文件 (libarclite_iphoneos.a)

如何以编程方式触发 SwiftUI DatePicker?

CGPath intersection(_:using:) 和朋友(iOS 16 中的新功能)坏了?

@Environment 的存在会导致列表在滚动时不断重建其内容

如何 comments .plist 文件中的行?

iOS 中的 Crashlytics 不会继续通过 Fabric 应用程序中的构建您的项目

没有 Mac 的 Xamarin Visual Studio IOS 开发?

刷新由 Xcode 7 管理的团队配置文件中的设备?

SRCROOT 和 PROJECT_DIR 有什么区别?

UITableView:从空白部分隐藏标题

如何在 iOS 中获取正在运行的应用程序的名称

如何找到 UILabel 的实际行数?

iOS 中的 Google Analytics SDK 3.0 _sqlite3 链接器错误

我可以在 UIScrollView 中使用 UIRefreshControl 吗?