Navid All Gharaee
Navid All Gharaee

Reputation: 109

Unexpected behavior when the constraints are applied for the first time

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:

enter image description here

And this is what I expect:

enter image description here

I can't get the layout I designed in the code unless I change device orientation once.

enter image description here

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

Answers (1)

Shehata Gamal
Shehata Gamal

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

Related Questions