Arthur Shkil
Arthur Shkil

Reputation: 362

How do you implement Size-Class-Specific Layout without storyboard?

I need to create a bit different versions of layout for different size classes, and I need to do that without storyboard.

I wonder what is the best way to do that? So far, I have two options:

1) Just remove all old constraints in traitCollectionDidChange() and set up new set of constraints.

2) Store all constraints in my ViewController and modify them in traitCollectionDidChange().

Second option seems to me to be better but I still have doubt :)

Upvotes: 0

Views: 288

Answers (1)

user7014451
user7014451

Reputation:

Store your constraints in your view controller - preferably in arrays if possible. Then, use viewWillTransition(to:size:) to activate/deactivate.

var wC = [NSLayoutConstraint]()
var wR = [NSLayoutConstraint]()
var hC = [NSLayoutConstraint]()
var hR = [NSLayoutConstraint]()

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)
    // use following two lines if width changes from compact to regular
    NSLayoutConstraint.deactivate(wC)
    NSLayoutConstraint.deactivate(wR)
}

Upvotes: 1

Related Questions