NSLayoutConstraints replaces the need for CGRects in Auto Layout. First describe the layout in words. Here, as I would describe your portrait example:
- Red width is 60% of its supervisor.
- Blue height is 55% of her supervisor.
- The blue left and right edges touch their supervisor.
- The red left edge touches your supervisor, the red right edge is close to the yellow left edge, and the yellow right edge touches his supervisor.
- The blue upper edge touches its supervisor, the blue lower edge is close to the red upper edge, and the red lower edge touches its supervisor.
- The blue lower edge is close to the yellow upper edge, and the yellow lower edge touches its superstructure.
Here's a method that removes existing superview constraints, then applies the new constraints to a given interface orientation.
- (void) buildConstriantsForInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Remove existing constraints. [superview removeConstraints:superview.constraints] ; // Build an array to hold new constraints. NSMutableArray* constraints = [NSMutableArray new] ; // Add 2 constraints that apply to both Portrait & Landscape orientations. [constraints addObject:[NSLayoutConstraint constraintWithItem:red attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:superview attribute:NSLayoutAttributeWidth multiplier:0.6 constant:0]] ; [constraints addObject:[NSLayoutConstraint constraintWithItem:blue attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:superview attribute:NSLayoutAttributeHeight multiplier:0.55 constant:0]] ; // Build a dictionary to store references to NSViews. NSDictionary* views = NSDictionaryOfVariableBindings(superview, blue, red, yellow) ; // To eliminate repeated NSLayoutConstraint code, build an array of Format Strings with which to build constraints. NSArray* formatStrings ; if ( UIInterfaceOrientationIsPortrait(interfaceOrientation) ) { formatStrings = @[@"H:|[blue]|", @"H:|[red]-[yellow]|", @"V:|[blue]-[red]|", @"V:[blue]-[yellow]|"] ; } else { formatStrings = @[@"H:|[blue]-[yellow]|", @"H:|[red]-[yellow]", @"V:|[blue]-[red]|", @"V:|[yellow]|"] ; } for ( NSString* formatString in formatStrings ) { [constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:formatString options:0 metrics:nil views:views]] ; } // Add the newly created constraints. [superview addConstraints:constraints] ; }
You can call this method whenever a view loads or rotates.
-(void) viewDidLoad { superview.translatesAutoresizingMaskIntoConstraints = NO ; [self buildConstriantsForInterfaceOrientation:self.interfaceOrientation] ; } - (void) willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration { [self buildConstriantsForInterfaceOrientation:toInterfaceOrientation] ; }
source share