在iOS中检测旋转变化

19

我正在制作一款iOS应用程序,需要在旋转时进行一些界面重新排列。我尝试通过实现- (void)orientationChanged:(NSNotification *)note来检测旋转,但这会通知我设备朝上或朝下的情况。

我想找到一种只在接口方向改变时得到通知的方法。

4个回答

28

有几种方法可以做到这一点,您可以在UIViewController类参考中找到它们:

 willRotateToInterfaceOrientation:duration:
 willAnimateRotationToInterfaceOrientation:duration:
 didRotateFromInterfaceOrientation:

你也可以在viewWillLayoutSubviews方法中实现它,但是要小心使用,因为它会在屏幕出现时以及每次添加子视图时调用。

编辑:

解决方案现已过时,请查看已接受的答案。


9
请注意,这三个在iOS 8中被废弃了。他们建议使用转换到大小的变体。 - Lawrence Kesteloot

24

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

5

Swift 3:

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

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接