添加带有约束的子视图不起作用

Add a subview with constraints do not work

我想添加一个带有一些约束的子视图。

但是我的观点没有出现。 下面是一些代码,有人知道哪里出了问题吗?

(如果我添加一个 UITextField,例如它工作正常...)

class TestViewController:UIViewController {
    override func viewDidLoad() {
        //Do not work...
        addAndLayout(v: UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 0)))


        //Works fine
        //addAndLayout(v: UITextField(frame: CGRect(x: 0, y: 0, width: 0, height: 0)))
    }

    func addAndLayout(v:UIView) {
        v.backgroundColor = UIColor.red
        view.addSubview(v)

        v.translatesAutoresizingMaskIntoConstraints = false
        let leading = NSLayoutConstraint(item: v, attribute: .leading, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0)
        let trailing = NSLayoutConstraint(item: v, attribute: .trailing, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0)
        let top = NSLayoutConstraint(item: v, attribute: .top, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: .top, multiplier: 1, constant: 0)
        view.addConstraints([leading, trailing, top])
    }
}

添加高度约束或底部约束,您应该会看到视图。它与 UITextField 一起工作的原因是 UITextField 具有固有的内容大小,而 UIView 没有。