【问题标题】:Set UIView size to fit subViews设置 UIView 大小以适应子视图
【发布时间】:2017-01-24 09:55:46
【问题描述】:

我有一个UIView,其中包含两个具有动态高度的 UILabel。我希望 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。

【问题讨论】:

  • 感谢您的回答,但据我所知,这个问题是关于如何使 UILabel 适合其文本,而不是如何使 UIView 适合 UILabel。
  • 不好意思,没用,我自己赶紧试了一下,补充了答案。

标签: ios swift uiview autolayout uilabel


【解决方案1】:

您可以使用情节提要本身来完成。

将视图的底部约束设置为第二个 UIlabel。所以当label的高度增加时,UIView的高度也会增加。

【讨论】:

  • 自动布局的最佳方式!
  • 它适用于UIView,但不适用于UICollectionViewCell
  • 我创建了这个问题stackoverflow.com/a/39527226/7767664 mb 有人知道如何使它与UICollectionViewCell 一起工作?
【解决方案2】:

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

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

    label1.sizeToFit()
    label2.sizeToFit()

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

    view.layoutSubviews()

【讨论】:

    猜你喜欢
    • 2011-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-05
    • 2014-09-21
    • 2017-06-08
    • 2014-09-02
    • 2013-04-12
    相关资源
    最近更新 更多