Search code examples
swiftuiviewconstraintsaddsubview

Add a subview with constraints do not work


I want to add a subview with some constraints.

But my view do not appear. Below is some code, does anyone know what is going wrong?

(If i add a UITextField e.g. it works fine...)

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

Solution

  • Add a height constraint or bottom constraint and you should see the view. The reason it works with UITextField is that UITextField has an intrinsic content size while UIView does not.