将UIView大小设置为适合子视图

21

我有一个包含两个动态高度UILabel的UIView。我希望UIView适应UILabel的大小+一些填充。目前,我绘制标签,然后将UIView的宽度和高度约束设置为标签的组合大小。

目前我正在这样做:

func populateWithMessage(headline: String?, message: String) {
    // Sets text
    self.headerLabel.text = headline
    self.messageLabel.text = message

    self.headerLabel.sizeToFit()
    self.messageLabel.sizeToFit()

    self.layoutSubviews()

    // Finding the label with the greatest width
    var longestLabel: UILabel!
    if self.headerLabel.frame.width > self.messageLabel.frame.width {
       longestLabel = self.headerLabel
   } else {
       longestLabel = self.messageLabel
   }
   
   let combinedLabelHeight = self.headerLabel.frame.height + self.messageLabel.frame.height
   
   // Update the container view's constraints
   self.containerViewWidtConstraint.constant = longestLabel.frame.width + 10
   self.containerViewHeightConstraint.constant = combinedLabelHeight + 10

   self.updateConstraints()
}

不幸的是它不起作用。我正在使用Swift 2.3和Autolayout。


这个答案可能会有用 https://dev59.com/JWQo5IYBdhLWcg3wfPfK - Carien van Zyl
谢谢您的回答,但据我所知,那个问题是关于如何使UILabel适应其文本,而不是如何使UIView适应UILabel。 - Nikolaj Simonsen
抱歉,它没有帮助。我自己快速尝试了一下并添加了一个答案。 - Carien van Zyl
2个回答

37

您可以使用故事板自身进行操作。

将视图的底部约束设置为第二个UILabel。因此,当标签的高度增加时,UIView的高度也会增加。

输入图片描述

输入图片描述


自动布局的最佳方式! - alexringo
1
它可以使用 UIView,但无法与 UICollectionViewCell 一起使用。 - user924
1
我创建了这个问题 https://dev59.com/lVkS5IYBdhLWcg3wu4rL#39527226,也许有人知道如何使它与`UICollectionViewCell`一起工作? - user924

5

@Girish M的回答是正确的。只是需要澄清一下。将顶部标签的约束设置为视图的顶部,两个标签之间的垂直间距以及底部标签和UIView之间的底部约束。不要设置任何高度约束。

或者,如果您想更加控制UILabel的高度,可以在storyboard中为标签添加高度约束,并在代码中创建出口。在更改标签文本时执行此代码。

    label1.sizeToFit()
    label2.sizeToFit()

    label1HeightConstraint.constant = label1.frame.size.height
    label2HeightConstraint.constant = label2.frame.size.height

    view.layoutSubviews()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接