检测 iOS 中的旋转变化
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14369251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Detect rotation changes in iOS
提问by Undo
I am making an iOS app that needs to do a little interface rearrangement upon rotation. I am trying to detect this by implementing - (void)orientationChanged:(NSNotification *)note
, but this gives me notifications for when the device is face up or face down.
我正在制作一个需要在旋转时进行一些界面重新排列的 iOS 应用程序。我试图通过实现来检测这一点- (void)orientationChanged:(NSNotification *)note
,但这会通知我设备何时面朝上或面朝下。
I want a way to just get notified when the interface changes orientations.
我想要一种在界面改变方向时得到通知的方法。
回答by Levi
There are several method where you can do that, you can find them in the UIViewController class reference:
有几种方法可以做到这一点,您可以在UIViewController 类参考中找到它们:
– 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.
您也可以在viewWillLayoutSubviews
方法中执行此操作,但要小心,因为它也会在屏幕外观上调用,并且每当您添加子视图时。
Edit:
编辑:
Solution now deprecated, see accepted answer.
解决方案现已弃用,请参阅已接受的答案。
回答by Stephen H King
Since iOS 8, above methods were deprecated, and the proper way to handle and detect device rotation is:
自 iOS 8 起,上述方法已被弃用,处理和检测设备旋转的正确方法是:
-(void) viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id )coordinator;
-(void) viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id )coordinator;
To detect device orientation, you should (according to documentation): call the statusBarOrientationmethod to determine the device orientation
要检测设备方向,您应该(根据文档):调用statusBarOrientation方法来确定设备方向
回答by PatrickDotStar
Since iOS 8 this is the correct way to do it.
从 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`
})
}
回答by NoLongerContributingToSE
Swift 3:
斯威夫特 3:
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
}