IOS/objective-C : MakeUILabel Flow to Multiple Lines with Autolayout

标签 ios autolayout uilabel

我试图让 UILabel 流向多行并使用自动布局将其下方的元素向下推。

这是我在 viewwillappear 中调用的代码。

self.myLabel.numberOfLines = 0;
self.myLabel.lineBreakMode = NSLineBreakByWordWrapping;
[_myLabel setContentCompressionResistancePriority:1000
               forAxis:UILayoutConstraintAxisVertical];
[self.myLabel setNeedsDisplay];
[self.myLabel layoutIfNeeded];
[self.view setNeedsDisplay];
[self.view layoutIfNeeded];

UILabel 被限制在内容 View 的顶部,它下面的图像被限制在 UILabel 的底部。该标签还具有 >=21 的高度限制。

在初始加载时,标签仅显示一行。

奇怪的是,在启动模态 VC 并关闭它之后,标签确实转到多行但无法下推其下方的元素。

在初始加载时。

enter image description here

启动和取消模态 VC 之后

enter image description here

我想知道问题是否与布局 subview 的时间有关,但我几乎尝试了所有方法。

提前感谢您的任何建议。

最佳答案

简单的例子:

  • 创建一个新的 ViewController。
  • 添加一个按钮,从顶部约束 40 磅并水平居中
  • 添加一个 UIView(绿色 View )。约束水平居中,宽度为 240,按钮的顶部空间为 20。
  • 向绿色 View 添加两个标签。
  • 顶部标签,行数 = 0,前导和尾随约束为 16,顶部约束为 8(到绿色 super View )
  • 底部标签,水平居中,顶部空间到顶部标签 8,底部约束 8(到绿色 super View )。
  • 将顶部标签连接到 View Controller 中的@IBOutlet var multiLineLabel: UILabel!
  • 将按钮 touch-up-inside 连接到 View Controller 中的 @IBAction func didTap(_ sender: Any) 函数。
  • 优先级没有变化。

运行应用程序。每次点击按钮都会向顶部/多行标签添加文本,并且会“下推”底部标签,而底部标签又会“下推”绿色 View 的底部边缘。

enter image description here

class ExpandingLabelViewController: UIViewController {

    @IBOutlet var multiLineLabel: UILabel!

    @IBAction func didTap(_ sender: Any) {

        if let s = multiLineLabel.text {

            multiLineLabel.text = s + " Here is some more text."

        }

    }

}

完成该操作后,您可以将其他元素添加到 View 中。只需确保您有一个垂直间距约束“链”,最顶部的元素被限制在绿色 super View 的顶部,最底部的元素被限制在绿色 super View 的底部。

关于IOS/objective-C : MakeUILabel Flow to Multiple Lines with Autolayout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49434441/

相关文章:

ios - 标签显示 html 数据并使图像和链接可快速点击

objective-c - Objective C - UILabel 多行垂直间隙高度

ios - 通过增加标签计数来添加图像

java - iOS 中的事件总线等效项

ios - UICollectionView,全宽单元格,允许自动布局动态高度?

swift - 将 CABasicAnimation 添加到子类 UIButton - 如果启用

uitableview - UIStackview 在 UITableviewCell 中按比例填充采用不正确的框架

ios - 找不到 Firebase 的 PhoneAuthProvider 类

ios - 从 NSMutableDictionary 中删除所有数据

ios - 是否可以在启用断点的情况下使用 XCode 的 Instruments?