【发布时间】: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