我需要检测设备何时处于纵向,以便触发特殊动画。但我不希望我的 View 自动旋转。
当设备旋转为纵向时,如何覆盖自动旋转的 View ?我的应用只需要以横向显示它的 View ,但如果我希望能够检测到纵向的旋转,我似乎也需要支持纵向。
最佳答案
在应用程序加载或 View 加载时尝试执行以下操作:
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter]
addObserver:self selector:@selector(orientationChanged:)
name:UIDeviceOrientationDidChangeNotification
object:[UIDevice currentDevice]];
然后添加如下方法:
- (void) orientationChanged:(NSNotification *)note
{
UIDevice * device = note.object;
switch(device.orientation)
{
case UIDeviceOrientationPortrait:
/* start special animation */
break;
case UIDeviceOrientationPortraitUpsideDown:
/* start special animation */
break;
default:
break;
};
}
以上将允许您注册设备的方向更改,而无需启用 View 的自动旋转。
注意
在 iOS 的所有情况下,当您添加观察者时,也要在适当的时候将其删除(可能,但不总是,当 View 出现/消失时)。您只能拥有“成对”的观察/不观察代码。如果您不这样做,应用程序将崩溃。选择观察/不观察的位置超出了本 QA 的范围。但是你必须有一个“unobserve”来匹配上面的“observe”代码。
关于ios - 检测 iOS UIDevice 方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9122149/