Search code examples
iosscreen-orientationdevice-orientation

willTransition function not working on a real device (swift 4)


I'm very new to iOS and swift, hope you guys can help me out. I'm working on a project where I have a side menu. When the device orientates from landscape to portrait or from portrait to landscape I want to make the side menu go away. I have this function:

override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {

    DispatchQueue.main.async{
        //do something here
        print("make side menu go away")
    }
}

This works on the simulator, but when I test it on a real device, it didn't work. Does anyone know what is going on? Or what is a better way to do this? Thanks in advance!


Solution

  • Change UIViewConrollerTransitionCoordinator to UIViewControllerTransitionCoordinator.

    Then tested on iOS 12 iPhone 6s, the method was called.

    EDIT

    You should use this method func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator)

    Or you could use this way:

        NotificationCenter.default.addObserver(self, selector: #selector(didRotate), name: UIDevice.orientationDidChangeNotification, object: nil)
    
        @objc func didRotate() {
          // Do something here
        }