What is wrong with this code? Why is the blue view not showing?
let myRedView = UIView(frame: CGRect(x: 0, y: 0, width: 400, height: 400))
myRedView.translatesAutoresizingMaskIntoConstraints = false
myRedView.backgroundColor = UIColor.redColor()
let myBlueView = UIView()
myBlueView.translatesAutoresizingMaskIntoConstraints = false
myBlueView.backgroundColor = UIColor.blueColor()
myRedView.addSubview(myBlueView)
let blueY = NSLayoutConstraint(item: myBlueView, attribute: .Left, relatedBy: .Equal, toItem: myRedView, attribute: .Right, multiplier: 1.0, constant: 10)
let blueX = NSLayoutConstraint(item: myBlueView, attribute: .Top, relatedBy: .Equal, toItem: myRedView, attribute: .Top, multiplier: 1.0, constant: 10)
//let blueWidth = NSLayoutConstraint(item: myBlueView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 200)
//let blueHeight = NSLayoutConstraint(item: myBlueView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 200)
myRedView.addConstraints([blueX,blueY])
With or without the width and height, it doesn't show and I don't understand the reason.
Another question I have about these constraints is who should I apply the .LeftMargin
. If to the main view on which I am modeling or to the second one.
If you use the
frame
normal you should not putfalse
the propertytranslatesAutoresizingMaskIntoConstraints
. Therefore, you must remove the following line:Tested on one
Playground
and it works perfectly.