Search code examples
iosautolayoutmasonry-ios-osx

Autolayout different constraints for landscape and portrait mode


I use Masonry library that helps with adding constraints programmatically. Its fine, but now i faced the problem that i need to uninstall and add new constraints after user rotate device from landscape to portrait. I tried rather "brutal" solution, it did change constraints, but, in fraction of second i could see "old" constraints. Is there are easy way to add/remove constraints after user rotate device? That is what i tried (it work, but as i described above in a fraction of second i could see "old" frames):

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation{

    if (UIInterfaceOrientationIsLandscape(self.interfaceOrientation)){
        [bottomRight mas_updateConstraints:^(MASConstraintMaker *make) {

            NSLog(@"We are on landscape");
            make.top.equalTo(upperRight.mas_bottom).with.offset(20);
            make.left.equalTo(self.view.mas_centerX).with.offset(20);
            make.right.equalTo(bottomRightRight.mas_left).with.offset(-20);
            make.bottom.equalTo(self.view.mas_bottom).with.offset(-100);

            make.width.equalTo(bottomRightRight);

        }]; }
    else {
        NSLog(@"Swapped");
        [bottomRight mas_updateConstraints:^(MASConstraintMaker *make) {

            make.top.equalTo(upperRight.mas_bottom).with.offset(200);
            make.left.equalTo(self.view.mas_centerX).with.offset(200);
            make.right.equalTo(bottomRightRight.mas_left).with.offset(-200);
            make.bottom.equalTo(self.view.mas_bottom).with.offset(-200);

            make.width.equalTo(bottomRightRight);

        }];

    }

}

Solution

  • i need to uninstall and add new constraints after user rotate device from landscape to portrait. I tried rather "brutal" solution, it did change constraints, but, in fraction of second i could see "old" constraints.

    But that's the problem: you are changing the constraints after the user rotates the device. So you are the one who is causing the phenomenon you don't like, i.e. that this happens a fraction of a second after the rotation is over.

    The correct solution is to change constraints before the user rotates the device. If you do that, the change of constraints will be magically animated to match the rotation and the change will appear absolutely seamless.

    For example, if this is an iPhone app, you can implement the view controller's willTransitionToTraitCollection... and do your constraint changes there, and the change will be magically matched to the rotation.