user3004445
user3004445

Reputation: 33

Xcode changing constraints dependant on screen orientation

I have designed an app using auto layout and all works perfectly, issue is, when I switch to landscape I want the location of one button to move to the other side of the screen.

Im assuming the best way of doing this is by changing the constraints when I rotate the screen, is this possible in the code, or even the best way of doing it? Obviously if the app starts up in landscape I obviously want this button to be in the landscape mode also.

thanks

Upvotes: 2

Views: 811

Answers (1)

matt
matt

Reputation: 535140

Absolutely. Remove and add constraints as desired in your view controller's updateViewConstraints implementation.

You will find it easiest to prepare both sets of alternate constraints beforehand, maintaining them in instance variables. Then you can just swap them in and out. Here's a sketch of what the code could look like:

-(void)updateViewConstraints {
    [self.view removeConstraints:self.oneSideConstraints];
    [self.view removeConstraints:self.otherSideConstraints];
    if (UIInterfaceOrientationIsLandscape(self.interfaceOrientation))
        [self.view addConstraints:self.oneSideConstraints];
    else
        [self.view addConstraints:self.otherSideConstraints];
    [super updateViewConstraints];
}

Upvotes: 4

Related Questions