First, disable automatic translation of autoResizingMasks to constraints.
1 |
[myView setTranslatesAutoresizingMaskIntoConstraints:NO]; |
Next, add the constraint for the fixed width.
1 2 3 4 |
[myView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[myView(==200)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(myView)]]; |
Finally, add the contraint for the fixed height.
1 2 3 4 |
[myView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[myView(==300)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(myView)]]; |
Note that I am setting a fixed width of 200 and a fixed height of 300.
Important note: Since we are adding our constraints programmatically, we need to do it in our UIViewController’s method:
1 |
- (void)updateViewConstraints |
(as stated in https://developer.apple.com/library/ios/featuredarticles/ViewControllerPGforiPhoneOS/AdoptingaFull-ScreenLayout/AdoptingaFull-ScreenLayout.html)
Also, remember to call [super updateViewConstraints]
when implementing the above method.
EDIT:
There is another way to define fixed width and height using constraints programmatically.
We can use NSLayoutAttributes to define this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
[myView addConstraint:[NSLayoutConstraint constraintWithItem:pageView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:300.0]]; [myView addConstraint:[NSLayoutConstraint constraintWithItem:pageView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:200.0]]; |
References: