【问题标题】:Anchor constraint shrinks superview instead of enlarging subview锚约束缩小超视图而不是放大子视图
【发布时间】: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


    【解决方案1】:

    缺少的一点是:

    _centralLabel.translatesAutoresizingMaskIntoConstraints = false
    

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

    _centralLabel = UILabel()
    

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

    【讨论】: