NSLayoutConstraints and setting the width/height of a view dynamically NSLayoutConstraints and setting the width/height of a view dynamically ios ios

NSLayoutConstraints and setting the width/height of a view dynamically


I wrote a little tool that will assist you with this:

http://autolayoutconstraints.com

Here is the answer to your question autogenerated by the tool

Objective-C

// align view from the left and right[self.containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[view]-10-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(view)]];// width constraint[self.containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[view(==250)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(view)]];// height constraint[self.containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[view(==50)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(view)]];

Swift

// align view from the left and rightself.containerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-10-[view]-10-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["view": view]));// width constraintself.containerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[view(==250)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["view": view]));// height constraintself.containerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[view(==50)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["view": view]));


To define the height and width of a view using layout constraints, you, uh, define the height and width of the view using layout constraints. For example, you are already saying:

NSArray *verticalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-50-[view]-250-|"     options:0 metrics:nil views:viewsDictionary];

So you could just change that to:

NSArray *verticalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(50)-[view(40)]"     options:0 metrics:nil views:viewsDictionary];

Now the view will be 50 pixels from the top of its superview, and 40 pixels tall.

Alternatively you can use constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant: to set the height constraint; the toItem will be nil, of course, since there is no relationship to another view.


Better later than never...

For Storyboard, IB and Swift:

Just control-drag your constraint like any other control to your viewController

@IBOutlet weak var spaceToTopThatIDecided: NSLayoutConstraint!

then change it simply:

spaceToTopThatIDecided.constant = 44

That's all!