Detect rotation changes in iOS

谁说我不能喝 提交于 2019-12-04 23:19:00

Since iOS 8, above methods were deprecated, and the proper way to handle and detect device rotation is:

-(void) viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id )coordinator;

To detect device orientation, you should (according to documentation): call the statusBarOrientation method to determine the device orientation

There are several method where you can do that, you can find them in the UIViewController class reference:

– willRotateToInterfaceOrientation:duration:
– willAnimateRotationToInterfaceOrientation:duration:
– didRotateFromInterfaceOrientation:

You could also do it in the viewWillLayoutSubviews method, but be careful with it, because it is called on the screen appearance too, and whenever you add a subview.

Edit:

Solution now deprecated, see accepted answer.

Swift 3:

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {

}

Since iOS 8 this is the correct way to do it.

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)

    coordinator.animate(alongsideTransition: { context in
        // This is called during the animation
    }, completion: { context in
        // This is called after the rotation is finished. Equal to deprecated `didRotate`
    })
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!