Vyachaslav Gerchicov
Vyachaslav Gerchicov

Reputation: 2457

Various autolayout constraints for different device orientations programmatically and without size classes?

The question is similar to this one: Autolayout and Device Orientation

But updateViewConstraints is never called (because nothing from mentioned methods is called on rotation, tested on iOS 9.1 simulator). In general it seems this topic doesn't contain a correct answer or the answers are too old.

I can't use size classes because the project should have also iOS 7 support and it supports size classes but with huge limitations.

It seems I need to clear and recreate all the constraints on each rotation event:

1)which method should recreate constraints?

2)how to recreate them at all? Maybe I remove them incorrectly:

for (UIView *v in self.view.subviews)
{
    v.translatesAutoresizingMaskIntoConstraints = NO;
}
for (UIView *v in self.view.subviews)
{
    [v removeConstraints:v.constraints];
    [self.view removeConstraints:v.constraints];
}
[self.view removeConstraints:self.view.constraints];

Or could you suggest a better way how to fix this issue?

Upvotes: 1

Views: 138

Answers (1)

Md1079
Md1079

Reputation: 1360

You could create two different sets of constraints programatically on viewDidLoad and only activate the ones you want to use

myPortraitConstraint = NSLayoutConstraint(item: someItem, attribute: .Left, relatedBy: .Equal, toItem: self, attribute: .Left, multiplier: 1.0, constant: 10
myPortraitConstraint.active = true

myLandscapeConstraint = NSLayoutConstraint(item: someItem, attribute: .Left, relatedBy: .Equal, toItem: self, attribute: .Left, multiplier: 1.0, constant: 0
myLandscapeConstraint.active = false

then on a rotation event switch the constraints you wish to use

myPortraitConstraint.active = false
myLandscapeConstraint.active = true
self.view.layoutIfNeeded()

Upvotes: 1

Related Questions