10

我正在制作一个需要在旋转时进行一点界面重排的iOS应用程序。我正试图通过执行- (void)orientationChanged:(NSNotification *)note来检测此问题,但是这会告知我设备何时正面朝上或正面朝下。在iOS中检测旋转更改

我想要一种方式来当界面改变方向时得到通知。

回答

26

有几种方法,你可以做到这一点,你可以在UIViewController class reference找到他们:

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

你也能做到这一点的viewWillLayoutSubviews方法,但要小心,因为它被称为上屏幕外观,以及每当你添加一个子视图。

编辑:

解决方案现在已经过时,见接受的答案。

+9

请注意,所有这三个都不推荐在iOS 8中使用。他们建议使用可以转换为大小的变体。 –

4

夫特3:

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

} 
1

从iOS 8开始,这是正确的方法。

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` 
    }) 
}