2016-09-16 23 views
2


我有一個UIView它包含兩個UILabels,它們具有動態高度。我想UIView適合UILabels +一些填充的大小。現在我正在繪製標籤,然後將UIView的寬度和高度約束設置爲標籤的組合大小。

現在我這樣做:設置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。

+0

這個答案可能是有用的http://stackoverflow.com/questions/16009405/uilabel-sizetofit-doesnt-work-with-autolayout-ios6 –

+0

謝謝您的回答,但據我所知,這個問題是關於如何使UILabel適合它的文本,而不是如何使UIView適合UILabel。 – NikMos

+0

對不起,它沒有幫助,我很快嘗試了自己,並添加了一個答案。 –

回答

12

你可以使用故事板本身。

將視圖的底部約束設置爲第二個UIlabel。所以當標籤的高度增加時,UIView的高度也會增加。

enter image description here

enter image description here

+0

它完美的作品:)謝謝! – NikMos

0

@Girish中號的答案是正確的。只是爲了澄清。將頂部標籤的約束設置爲視圖的頂部,兩個標籤之間的垂直間距以及底部標籤和UIView之間的底部約束。不要設置任何高度限制。

或者,如果您想更多地控制UILabels的高度,可以在故事板中爲標籤添加高度約束,並在代碼中爲它們創建出口。更改標籤文本時執行此代碼。

label1.sizeToFit() 
    label2.sizeToFit() 

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

    view.layoutSubviews()