If I define my constraints in IB, I can still resize the window that houses the subview.
![enter image description here](https://i.stack.imgur.com/GXkJSm.png)
All the other constraints are the same, but to left, right, and bottom.
When I try to do this in code, I can no longer resize the superview (NSWindow) by hand at runtime, nor maximize it:
class ViewController: NSViewController {
@IBOutlet var box : NSBox!
func matchAttribute(attribute: NSLayoutAttribute, view: NSView, superview: NSView) {
var constraint = NSLayoutConstraint(item: view, attribute: attribute, relatedBy: NSLayoutRelation.Equal, toItem: superview, attribute: attribute, multiplier: 1, constant: 0)
constraint.priority = 1000
superview.addConstraint(constraint)
}
override func viewDidLoad() {
super.viewDidLoad()
self.matchAttribute(NSLayoutAttribute.Top, view: self.box, superview: self.box.superview!)
self.matchAttribute(NSLayoutAttribute.Trailing, view: self.box, superview: self.box.superview!)
self.matchAttribute(NSLayoutAttribute.Leading, view: self.box, superview: self.box.superview!)
self.matchAttribute(NSLayoutAttribute.Bottom, view: self.box, superview: self.box.superview!)
}
}
What must I do to get the same Autolayout behavior programmatically?
Because you aren't adding any constraints to your box in Interface Builder, at the point it loads it is considered to have an ambiguous layout. To remove this ambiguity, Cocoa automatically adds some constraints:
You'll note that the combined effect of the last two constraints is to fix the width and height of the box - this is why you cannot resize the window, because doing so would violate these constraints.
To get the effect you want, you first need to remove these auto-generated constraints: