Can I use autolayout to provide different constraints for landscape and portrait orientations?

后端 未结 6 1848
旧巷少年郎
旧巷少年郎 2020-12-01 03:44

Is it possible to change the constraints when the device is rotated? How might this be achieved?

A simple example might be two images which, in portrait, are stacked

6条回答
  •  独厮守ぢ
    2020-12-01 04:11

    The approach I am using (for better or worse) is to define both sets of constraints (portrait and landscape) in the storyboard editor.

    To avoid the storyboard warnings of hell, I place all of one set at a priority of 999, just so it doesn't show red everywhere.

    Then I add all of the constraints to outlet collections:

    @property (strong, nonatomic) IBOutletCollection(NSLayoutConstraint) NSArray *portraitConstraints;
    @property (strong, nonatomic) IBOutletCollection(NSLayoutConstraint) NSArray *landscapeConstraints;
    

    Finally, I implement my ViewControllers's viewWillLayout method:

    - (void) viewWillLayoutSubviews {
        [super viewWillLayoutSubviews];
        for (NSLayoutConstraint *constraint in self.portraitConstraints) {
            constraint.active = (UIApplication.sharedApplication.statusBarOrientation == UIDeviceOrientationPortrait);
        }
        for (NSLayoutConstraint *constraint in self.landscapeConstraints) {
            constraint.active = (UIApplication.sharedApplication.statusBarOrientation != UIDeviceOrientationPortrait);
        }
    }
    

    This seems to work. I really wish you could set the default active property in the the storyboard editor.

提交回复
热议问题