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

时间:2017-02-11 09:01:34

标签: swift uiview constraints addsubview

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

但我的观点没有出现。 下面是一些代码,有谁知道出了什么问题?

(如果我添加一个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])
    }
}

1 个答案:

答案 0 :(得分:3)

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

相关问题