The issue is that you're calling [super updateViewConstraints]
in updateViewConstraints
while you still have constraints in place for the button. So, as you transition from landscape to portrait, you still have the landscape button constraints (which are unsatisfiable in portrait), but are asking the main view to update its (portrait) constraints. If you move the call to [super updateViewConstraints]
anywhere after you remove all of your existing button constraints, and you should be in good shape.
A couple of asides:
If using storyboards/NIBS, you should remove the line that says:
self.view.translatesAutoresizingMaskIntoConstraints = NO;
But keep the line that says:
_button1.translatesAutoresizingMaskIntoConstraints = NO;
I'd be wary of a wholesale removal of all constraints. I usually keep arrays of the constraints I want to remove, and that way I can easily remove just the ones that I need removing and will be reconstructing. In your case, removing all is probably fine, but as you add more and more constraints to your view, it's probably just easier to keep track of which you want to remove and reconstruct:
@property (nonatomic, strong) NSArray *verticalConstraints; @property (nonatomic, strong) NSArray *horizontalConstraints;
I might suggest using VFL, which is a little more concise:
- (void)updateViewConstraints { if (self.horizontalConstraints) [self.view removeConstraints:self.horizontalConstraints]; if (self.verticalConstraints) [self.view removeConstraints:self.verticalConstraints]; [super updateViewConstraints]; NSDictionary *views = NSDictionaryOfVariableBindings(_button1); NSDictionary *metrics = nil; if (UIInterfaceOrientationIsPortrait([UIApplication sharedApplication].statusBarOrientation)) { metrics = @{@"left" : @100, @"right" : @100, @"top" : @200, @"bottom" : @100}; _button1.backgroundColor = [UIColor redColor]; } else{ metrics = @{@"left" : @200, @"right" : @200, @"top" : @50, @"bottom" : @50}; _button1.backgroundColor = [UIColor blueColor]; } self.horizontalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(left)-[_button1]-(right)-|" options:0 metrics:metrics views:views]; self.verticalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(top)-[_button1]-(bottom)-|" options:0 metrics:metrics views:views]; [self.view addConstraints:self.horizontalConstraints]; [self.view addConstraints:self.verticalConstraints]; }