首页 > 解决方案 > 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!

标签: iosscreen-orientationdevice-orientation

解决方案


更改UIViewConrollerTransitionCoordinatorUIViewControllerTransitionCoordinator

然后在iOS 12 iPhone 6s上测试,调用了该方法。

编辑

你应该使用这个方法 func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator)

或者你可以这样使用:

    NotificationCenter.default.addObserver(self, selector: #selector(didRotate), name: UIDevice.orientationDidChangeNotification, object: nil)

    @objc func didRotate() {
      // Do something here
    }

推荐阅读