简体   繁体   中英

Auto layout orientation change for portrait but not horizontal

I designed the layout of my app with a landscape orientation, but when it's in portrait orientation it looks too cramped. When it's in portrait I want to shift all of my UILabels down by 10 or so pixels. I tried doing this by setting an upper constraint with auto layout. And I was able to get the position I want in portrait, but it changes the positions of the UILabels for the landscape orientation as well. I thought about turning all of the labels to IBOutlets and change their positions programmatically. But I was wondering if there was an easier or more efficient solution?

You can add constraints to the UILabels, and change them when you change orientations. For instance, add a constraint to a UILabel making it x pixels from the top of the screen. When you move to portrait orientation, you can update the constraint to be x + 10.

@interface YourClass()

@property (nonatomic, strong) UILabel *label;
@property (nonatomic, strong) NSLayoutConstraint *constraint;

@end

@implementation YourClass

- (void)setupConstraints {
    self.constraint = [NSLayoutConstraint constraintWithItem:self.label
                                                   attribute:NSLayoutAttributeTop
                                                   relatedBy:NSLayoutRelationEqual
                                                      toItem:self.view
                                                   attribute:NSLayoutAttributeHeight
                                                  multiplier:0
                                                    constant:20];
}

// Call this method every time orientation changes.
- (void)updateConstraints {
    if([[UIDevice currentDevice] orientation] == UIDeviceOrientationPortrait) {
        self.constraint.constant = 30;
    } else {
        self.constraint.constant = 20;
    }
}

@end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM