1
votes

I was messing with layoutSubviews method in UIViewControllers. I assumed that when you override layoutSubviews on the view, it doesn't layout its subviews, but that wasn't the case, the view and its subviews were correctly laid out.

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)
    }
}

I expected that because I was not calling layoutSubviews, my views wouldn't be laid out, but I get layout like if I did override this method.

enter image description here

1

1 Answers

0
votes

Read the docs: https://developer.apple.com/documentation/uikit/uiview/1622482-layoutsubviews

"the default implementation uses any constraints you have set to determine the size and position of any subviews. Subclasses can override this method as needed to perform more precise layout of their subviews."