Reputation: 109
I want to change the layout and constraints relative to the orientation of the device. Here's how I implemented it:
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
addViews()
constraintSubviews()
}
func constraintSubviews() {
if UIDevice.current.orientation.isPortrait {
NSLayoutConstraint.activate(portraitConstrains)
NSLayoutConstraint.deactivate(landscapeConstrains)
NSLayoutConstraint.activate(nowPlayingView.portraitConstrains)
NSLayoutConstraint.deactivate(nowPlayingView.landscapeConstrains)
} else {
NSLayoutConstraint.deactivate(portraitConstrains)
NSLayoutConstraint.activate(landscapeConstrains)
NSLayoutConstraint.activate(nowPlayingView.landscapeConstrains)
NSLayoutConstraint.deactivate(nowPlayingView.portraitConstrains)
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
constraintSubviews()
}
Here's what I ended up when running the code:
And this is what I expect:
I can't get the layout I designed in the code unless I change device orientation once.
Better implementation
I've searched all over the Internet and the best thing I found was this implementation. Is there a better implementation regarding this subject?
Upvotes: 2
Views: 147
Reputation: 100533
You need
1- Make deactivate before activate
func constraintSubviews() {
if UIDevice.current.orientation.isPortrait {
NSLayoutConstraint.deactivate(landscapeConstrains)
NSLayoutConstraint.deactivate(nowPlayingView.landscapeConstrains)
NSLayoutConstraint.activate(nowPlayingView.portraitConstrains)
NSLayoutConstraint.activate(portraitConstrains)
} else {
NSLayoutConstraint.deactivate(portraitConstrains)
NSLayoutConstraint.deactivate(nowPlayingView.portraitConstrains)
NSLayoutConstraint.activate(landscapeConstrains)
NSLayoutConstraint.activate(nowPlayingView.landscapeConstrains)
}
}
2- Replace
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
constraintSubviews()
}
with
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.willTransition(to: size, with: coordinator)
constraintSubviews()
}
Upvotes: 2