Default missing Autolayout constraints when added programmatically

时间:2019-01-18 18:09:54

标签: swift autolayout nslayoutconstraint

I forgot to add an x-component to my autolayout, but I was still able to see the view. I was wondering how/if autolayout generates default constraints when used programatically because in IB, there would be errors. No errors are printed in the debug console for this either.

I notice that when I do not specify an x-component, the view will always be left anchored to its parent view. Is there documentation which states what the default values are when a constraint is missing?

enter image description here

import UIKit
import PlaygroundSupport
//
class MyViewController : UIViewController {

    override func loadView() {
        let view = UIView()
        view.backgroundColor = .white
        self.view = view
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let outBox = UIView()
        outBox.backgroundColor = UIColor.blue
        view.addSubview(outBox)
        outBox.translatesAutoresizingMaskIntoConstraints = false
        outBox.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        outBox.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
        outBox.widthAnchor.constraint(equalToConstant: 200).isActive = true
        outBox.heightAnchor.constraint(equalToConstant: 200).isActive = true

        let inBox = UIView(frame: CGRect(x: 100, y: 2000, width: 10, height: 10))
        inBox.backgroundColor = UIColor.red
        outBox.addSubview(inBox)
        inBox.translatesAutoresizingMaskIntoConstraints = false
        inBox.topAnchor.constraint(equalTo: outBox.topAnchor).isActive = true
        inBox.bottomAnchor.constraint(equalTo: outBox.bottomAnchor).isActive = true
        inBox.widthAnchor.constraint(equalToConstant: 25).isActive = true
        // NO x-constraint component.. Should raise missing constraints error.
    }
}

PlaygroundPage.current.liveView = MyViewController()

1 个答案:

答案 0 :(得分:1)

The key isn't in setting frame here

let inBox = UIView(frame: CGRect(x: 100, y: 2000, width: 10, height: 10))

but it's here

inBox.translatesAutoresizingMaskIntoConstraints = false

that line ignores the internal conversion of frame to constraints and defaults them to zero based , insuffieicent constraints don't mean you can't see the view , for example you can do the same in IB and still see the view with red border and after run also but it doesn't mean it's properly set , and this as finally constraints will be converted to frame so it's a coincidence regarding zero-based