【发布时间】:2026-02-17 23:10:01
【问题描述】:
通过从库中拖动 UIView 对象,自定义视图位于 IB 中,并且它的类名设置为自定义视图类名。这个自定义视图有一个子视图,在init?(coder aDecoder: NSCoder)中添加。
锚类型约束应该如何组成,它们应该放在哪里,以便在自定义视图中集中设置_centralLabel子视图,并且它的尺寸是自定义视图尺寸的25%?
如果代码是这样写的:
override func updateConstraints() {
if !_subviewsConstraintsAdded {
_centralLabel.heightAnchor.constraint(equalTo: heightAnchor, multiplier: 0.25).isActive = true
_centralLabel.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 0.25).isActive = true
_centralLabel.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
_centralLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
_subviewsConstraintsAdded = true
}
super.updateConstraints()
}
代码的结果是,不是将 _centralLabel 的大小设置为自定义视图的 25%,而是将自定义视图缩小到 (0,0),即 _centralLabel 的大小,而 updateConstraints()调用。
【问题讨论】:
标签: ios uiview nslayoutconstraint ios-autolayout layout-anchor