Andrii Chernenko
Andrii Chernenko

Reputation: 10204

Autolayout: Specify spacing between view and navigation bar

I'm trying to figure out what constraints I should set to place view below navigation bar. The problem is that its height depends on current orientation (44 in portrait, 32 in landscape), so I can't use the exact number.

portrait landscape

Is there any special value I can use for the constraint?

Upvotes: 0

Views: 1760

Answers (3)

Andrii Chernenko
Andrii Chernenko

Reputation: 10204

Using top and bottom layout guides to create constraints would probably be the correct solution, but they are available only in Storyboard mode.

In case they are not available (or don't work for some reason), solution is the following:

  1. Create constraint relative to superview top (actual value doesn't matter at this point, we will set it in code).
  2. Create outlet for constraint from step 1 (the same way you would for a view).
  3. Modify your view controller code:
 
- (void)viewDidLoad {
    //initial setup
    UIInterfaceOrientation currentOrientation = [UIApplication sharedApplication].statusBarOrientation;
    [self applyTopBarOffsetForOrientation:currentOrientation];
}

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
    [self applyTopBarOffsetForOrientation:toInterfaceOrientation];
}

- (void)applyTopBarOffsetForOrientation:(UIInterfaceOrientation) orientation {
    BOOL isPhone = [UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPhone;
    self.topBarSpacingConstraint.constant = UIDeviceOrientationIsLandscape(orientation) && isPhone ? 52 : 64;
}

Upvotes: 0

David Berry
David Berry

Reputation: 41226

This is precisely why iOS 7 provides the Top Layout Guide and Bottom Layout Guide Create your restraint relative to them and the right thing will happen.

Upvotes: 1

smyrgl
smyrgl

Reputation: 854

Constraints

See that top constraint that is highlighted? That will let you set a fixed distance to a neighboring view. The problem is that your navigation bar is likely on top of the embedded view which means you need to uncheck the "Under Top Bars" setting and then you will be able to set a constraint to the top layout manager.

enter image description here

Upvotes: 3

Related Questions