Search code examples
swiftautolayoutorientationsnapkit

Auto-Layout [Snapkit] change constraints on rotate


I have built an app that uses no interface builder using Snapkit to create my Auto-Layout constraints. Everything looks fine in portrait, however a few screen's need some landscape specific constraints.

I've searched here and Google in general for a quick intro on doing this, but couldn't really find anything that was applicable (everything I found was based on using IB or used size classes instead of orientation - I specifically want landscape, not compact vs regular).

So, all my auto-layout constraints are set up in viewDidLoad at the moment. No doubt at very least, the ones that will be orientation dependant need moving to some kind of delegate/callback method on UIViewController, but I don't know know what that is...

  1. How do I detect an orientation change in order to change my constraints?
  2. How do I get the current orientation (so when I first load the view controller I can set the right constraints... Or is the function from my above question always called at least once for each VC on load?)
  3. Outside of a ViewController, such as custom UIView's, how do I detect the orientation change? Should i send out a custom notification event? I'd rather not have my UIViewController tell every subview it has that orientation has changed.

Thanks for any help :)


Solution

  • I would personally use this function:

        override func viewWillTransitionToSize(size: CGSize, 
        withTransitionCoordinator coordinator: 
        UIViewControllerTransitionCoordinator) {}

    And then when those changes are detected call setNeedsLayout and layoutIfNeeded which should trigger a redraw of all of your subviews which can then handle setting constraints for specific orientations