以编程方式添加时默认缺少自动布局约束

Default missing Autolayout constraints when added programmatically

我忘记在我的自动版式中添加 x-component,但我仍然可以看到视图。我想知道 how/if autolayout 在以编程方式使用时会生成默认约束,因为在 IB 中,会有错误。调试控制台中也没有打印任何错误。

我注意到当我不指定 x-component 时,视图将始终锚定到其父视图。是否有文档说明缺少约束时的默认值?

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

关键不在此处设置框架

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

但它就在这里

inBox.translatesAutoresizingMaskIntoConstraints = false

该行忽略了框架到约束的内部转换并将它们默认为基于零的约束,不充分的约束并不意味着您看不到视图,例如您可以在 IB 中执行相同的操作并且仍然可以看到视图带有红色边框和 运行 之后,但这并不意味着它已正确设置,并且这作为最终约束将转换为框架,因此对于基于零的

是巧合