首页 > 解决方案 > UIKit 布局子视图,即使它没有被要求

问题描述

我在 UIViewControllers 中弄乱了 layoutSubviews 方法。我假设当您在视图上覆盖 layoutSubviews 时,它不会布局其子视图,但事实并非如此,视图及其子视图已正确布局。

class Vieww: UIView {
    override func didMoveToSuperview() {
        super.didMoveToSuperview()
        let centered = UIView()
        addSubview(centered)
        centered.translatesAutoresizingMaskIntoConstraints = false
        backgroundColor = .green
        centered.backgroundColor = .red
        centered.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 1/2).isActive = true
        centered.heightAnchor.constraint(equalTo: heightAnchor, multiplier: 1/2).isActive = true
        centered.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
        centered.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
    }
    override func layoutSubviews() {
        print("layoutSubviews")
    }
}

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        view.layout(Vieww()).center().leading(20).trailing(20).height(400)
    }
}

我预计因为我没有调用 layoutSubviews,所以我的视图不会被布置,但我得到的布局就像我确实覆盖了这个方法一样。

在此处输入图像描述

标签: iosswiftuser-interfaceautolayoutconstraints

解决方案


阅读文档:https ://developer.apple.com/documentation/uikit/uiview/1622482-layoutsubviews

“默认实现使用您设置的任何约束来确定任何子视图的大小和位置。子类可以根据需要覆盖此方法以执行其子视图的更精确布局。”


推荐阅读