繁体   English   中英

UIKit 布局子视图,即使它没有被要求

[英]UIKit layouts subviews even though it was not asked to

我在 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,所以我的视图不会被布置,但我得到的布局就像我确实覆盖了这个方法一样。

在此处输入图像描述

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM