0

通过从库中拖动 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%,而是在调用 updateConstraints() 时将自定义视图缩小到 (0,0),即 _centralLabel 的大小。

4

1 回答 1

0

缺少的一点是:

_centralLabel.translatesAutoresizingMaskIntoConstraints = false

在使用以下行以编程方式实例化子视图后,它应该位于某处:

_centralLabel = UILabel()

在此修正之后,_centralLabel 子视图已放大并已移动到视图的中心,而视图本身仍保持其原始大小、形状和位置。

于 2017-01-18T11:27:11.633 回答