Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ios change constraint programmatically

I am using autolayout with a constraint. The top space to superview is 100

I now want to change this so that when the user rotates the device to landscape The top space to superview is 50

Can this be done at design time?

How can this be done at runtime?

like image 429
OneGuyInDc Avatar asked Mar 20 '14 18:03

OneGuyInDc


People also ask

How do I change constraints in Xcode?

Some editing is also possible directly from the Size inspector. Clicking the Edit button in any of the constraints brings up a popover where you can change the constraint's relationship, constant, priority, or multiplier.

How do I change the constraint multiplier in Swift?

Since multiplier is a read-only property and you can't change it, you need to replace the constraint with its modified clone.


1 Answers

Well, if your 50 px for landscape and 100 for portrait can somehow be derived by relations to sibling subviews and fixed offsets to the bounds of superview, then yes, this can be done "at design time", and that's actually what auto layout is meant to be for.

Otherwise you would need to have a reference to the constraint, then in willRotateToInterfaceOrientation:duration: method you need to change the value of the constant of this constraint and call layoutIfNeeded for the superview.

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];

    self.myConstraint.constant = (UIInterfaceOrientationIsLandscape(toInterfaceOrientation)) ? 50. : 100.;
    [self.someView layoutIfNeeded];
}

(written in the browser, might have mistakes)

like image 96
dariaa Avatar answered Sep 20 '22 15:09

dariaa