我有一個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。
這個答案可能是有用的http://stackoverflow.com/questions/16009405/uilabel-sizetofit-doesnt-work-with-autolayout-ios6 –
謝謝您的回答,但據我所知,這個問題是關於如何使UILabel適合它的文本,而不是如何使UIView適合UILabel。 – NikMos
對不起,它沒有幫助,我很快嘗試了自己,並添加了一個答案。 –