我有一个UIView,其中包含两个具有动态高度的UILabel。我希望UIView适合UILabels的大小+一些填充。现在,我正在绘制标签,然后将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。

最佳答案

您可以使用 Storyboard 本身来完成。

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

ios - 设置UIView大小以适合subViews-LMLPHP

ios - 设置UIView大小以适合subViews-LMLPHP

关于ios - 设置UIView大小以适合subViews,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39526929/

10-11 22:14
查看更多