ios 设置 UIView 大小以适合子视图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39526929/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set UIView size to fit subViews
提问by Nikolaj Nielsen
I'm having a UIView
that's containing two UILabels, which have dynamic heights. I want the UIView
to fit the size of the UILabels + some padding. Right now I'm drawing the labels and then sets the UIView's width and height constraints to the combined size of the labels.
Right now I'm doing this:
我有一个UIView
包含两个具有动态高度的 UILabels。我想要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()
}
Unfortunately it doesn't work :-/
Any ideas will be much appreciated!
I'm using Swift 2.3 and Autolayout.
不幸的是它不起作用:-/
任何想法将不胜感激!
我正在使用 Swift 2.3 和 Autolayout。
回答by miOS
回答by Carien van Zyl
@Girish M answer is correct. Just to clarify. Set the top label's constraint to the views' top, vertical spacing between the two labels and a bottom constraint between the bottom label and UIView. Do not set any height constraints.
@Girish M 答案是正确的。只是为了澄清。将顶部标签的约束设置为视图的顶部,两个标签之间的垂直间距以及底部标签和 UIView 之间的底部约束。不要设置任何高度限制。
Alternatively, if you want a bit more control over the heights of the UILabels, you can add height constraints in storyboard for the labels and create outlets for them in your code. Perform this code when changing the text of the labels.
或者,如果您想要更多地控制 UILabels 的高度,您可以在故事板中为标签添加高度约束,并在您的代码中为它们创建出口。更改标签文本时执行此代码。
label1.sizeToFit()
label2.sizeToFit()
label1HeightConstraint.constant = label1.frame.size.height
label2HeightConstraint.constant = label2.frame.size.height
view.layoutSubviews()