You can use the priority of NSLayoutConstraint
Auto Layout set views with higher priority of constraints.
for Portrait
Set the priority of leading and top space constraints of square views to low value (750 or lower than 1000). Default priority value is 1000.
In Interface Builder, You can set the priority in Attribute Inspector.
for Landscape
Create constraints in code for landscape mode.
The constraints should have higher priority than portraits. Keep the constraints in array and add or remove constraints in viewWillLayoutSubviews
method of UIViewController.
Test code in following.
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIView *view1; // square 1
@property (weak, nonatomic) IBOutlet UIView *view2; // square 2
@property (weak, nonatomic) IBOutlet UIView *view3; // square 3
@end
@implementation ViewController{
NSMutableArray *_constraintsList;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_constraintsList = [NSMutableArray new];
// constraints for Landscape mode
// this constraints has 1000 priority. (default value)
// please modify offset value (20 or 40) to match your case.
NSDictionary *views = @{@"view1": self.view1, @"view2": self.view2,@"view3": self.view3};
[_constraintsList addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-20-[view1]-20-[view2]-20-[view3]"
options:0 metrics:nil
views:views]];
[_constraintsList addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-40-[view2]" options:0 metrics:nil views:views]];
[_constraintsList addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-40-[view3]" options:0 metrics:nil views:views]];
}
-(void)viewWillLayoutSubviews{
[super viewWillLayoutSubviews];
UIInterfaceOrientation currentOrientation = [UIApplication sharedApplication].statusBarOrientation;
if(currentOrientation == UIInterfaceOrientationPortrait){
// in portrait mode.
// new constraints is not necessary.
[self.view removeConstraints:_constraintsList];
}else if(currentOrientation == UIInterfaceOrientationLandscapeLeft){
// for landscape mode
// add new constraints. then auto layout adjust view to fit new higher constraints
[self.view addConstraints:_constraintsList];
}
}