【发布时间】:2018-02-04 14:44:44
【问题描述】:
我有以下设置: UIView 以编程方式添加一堆子视图 (UILabels),并设置自动布局约束,以便标签之间和 UIViews 边缘之间的距离各为 10。目标是 UIView 根据所有子视图(带有动态文本的标签)的内容(包括空格)设置其大小。
我使用以下代码,但它似乎不起作用。 UIView 不会调整大小,它会缩小标签。
// setup of labelList somewhere else, containing the label data
var lastItemLabel: UILabel? = nil
var i = 1
for item in itemList {
let theLabel = UILabel()
// ... label setup with text, fontsize and color
myView.addSubview(theLabel)
theLabel.translatesAutoresizingMaskIntoConstraints = false
// If it is the second or more
if let lastLabel = lastItemLabel {
theLabel.leadingAnchor.constraint(equalTo: lastLabel.trailingAnchor, constant: 12).isActive = true
theLabel.topAnchor.constraint(equalTo: myView.topAnchor, constant: 10).isActive = true
// if it is the last label
if i == labelList.count {
theLabel.trailingAnchor.constraint(equalTo: myView.trailingAnchor, constant: 12).isActive = true
}
}
// If it is the first label
else {
theLabel.leadingAnchor.constraint(equalTo: myView.leadingAnchor, constant: 12).isActive = true
theLabel.topAnchor.constraint(equalTo: myView.topAnchor, constant: 10).isActive = true
}
lastItemLabel = theLabel
i += 1
}
【问题讨论】:
-
您是否将
myView添加到滚动视图中?如果不是,它是如何限制在它的 superview 上的? -
myView 是主视图(出口)内故事板中的 UIView
-
那么要问的问题是您对故事板中的
myView有什么限制? (原谅我,@Paulw11 已经问过了。) -
确保在更新约束时调用 setNeedsLayout...developer.apple.com/documentation/uikit/uiview/… 或 layoutIfNeeded developer.apple.com/documentation/uikit/uiview/…
-
如果
myView被限制在场景根视图中,那么它永远不会变得更大。您将需要使用滚动视图。
标签: ios swift autolayout