ios - 设置 UIView 大小以适应 subview

标签 ios swift uiview autolayout uilabel

我有一个 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 和自动布局。

最佳答案

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

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

enter image description here

enter image description here

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

相关文章:

ios - 如何拖动和关闭 View Controller ?

ios - 由于单元格为空,如何检索 UserDefaults

ios - 在 didSelectRowAtIndexPath 中更改自定义 UIImage

swift - 如何放置一个始终看着相机的 RealityKit 实体?

ios - SceneKit 支持的 OpenGL ES 3.0 子集是什么?

ios - 如何在 swift 2.0 的 UITextfield 中只允许特定的一组数字

ios - 通过 hitTest 在 Swift 中关闭键盘

ios - Swift MKMapView KVO

swift - 自定义 UIView 作为背景

ios - 如何创建一个动态弹出的 SubView 并扩展它的 super View 大小。 (在代码中)