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

后端 未结 6 1853
旧巷少年郎
旧巷少年郎 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:00

    My idea is to handle orientation by changing constraint priorities.
    Supposing priorities will be:

    • landscape: 910 active / 10 inactive.
    • portrait: 920 active / 20 inactive.

    Step 1: Create landscape (or portrait) design in Storyboard with constraints.
    Step 2: For constraints, that must be active only for landscape mode set priority to 10.
    Step 3: Add constraints for portrait mode and set their priority to 920.

    In willAnimateRotationToInterfaceOrientation add code:

    for (NSLayoutConstraint *constraint in myView.constraints) {
        if (UIInterfaceOrientationIsLandscape(UIApplication.sharedApplication.statusBarOrientation)) {
            if (constraint.priority == 10)  constraint.priority = 910;
            if (constraint.priority == 920) constraint.priority = 20;
        } else {
            if (constraint.priority == 20)  constraint.priority = 920;
            if (constraint.priority == 910) constraint.priority = 10;
        }
    }
    

    Advantage of this approach - easy adjusting in Interface Builder. When we need to switch to any orientation, we select all constraints by priority and change them simultaneously (910->10, 20->920):

    Interface will rebuilded automatically.

提交回复
热议问题