Detect end of transition?

Hi,


I'm familiar with the "willTransition" method of view controllers that lets you detect when a transition to a new UITraitCollection is about to begin.


What I need is a callback that happens after the transition is finished. There doesn't seem to be any "didTransition" method, nor any delegate property on the UIViewControllerTransitionCoordinator that I can use for this.


How does one obtain this callback?


Thanks,

Frank

Replies

Did you try to use:


func viewDidLayoutSubviews()

Called to notify the view controller that its view has just laid out its subviews.


This happens after layout has been changed for orientation.


That is not only called for orientation change. You could thus set a flag in viewWillTranstion to test in didLayout


    fileprivate var rotate = false

    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
        rotate = true
        sleep(3)     // JUST for test, to see we wait till transition is done
    }

    override func viewDidLayoutSubviews() {
        if rotate {
            print("End of rotation")
            rotate = false
        }
    }

Taken and edited from this Stackoverflow. Use coordinator.animate to determine when the animation is over.

class ViewController: UIViewController {
   public override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {        
        super.viewWillTransition(to: size, with: coordinator)
        coordinator.animate(alongsideTransition: { (context) in
            guard let windowInterfaceOrientation = self.windowInterfaceOrientation else { return }
            
            if windowInterfaceOrientation.isLandscape {
                // activate landscape changes
            } else {
                // activate portrait changes
            }
        })
    }
    
    private var windowInterfaceOrientation: UIInterfaceOrientation? {
        return UIApplication.shared.windows.first?.windowScene?.interfaceOrientation
    }
}