检测iOS UIDevice方向 [英] Detecting iOS UIDevice orientation

查看:120
本文介绍了检测iOS UIDevice方向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检测设备何时处于纵向方向,以便我可以触发特殊动画。但我不希望我的视图自动旋转。

I need to detect when the device is in portrait orientation so that I can fire off a special animation. But I do not want my view to autorotate.

当设备旋转为纵向时,如何覆盖自动旋转视图?我的应用程序只需要在横向显示它的视图,但似乎我还需要支持肖像,如果我想能够检测旋转到肖像。

How do I override a view autorotating when the device is rotated to portrait? My app only needs to display it's view in landscape but it seems I need to support portrait also if I want to be able to detect a rotation to portrait.

推荐答案

在加载应用程序或加载视图时尝试执行以下操作:

Try doing the following when the application loads or when your view loads:

[[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;
   };
}

以上将允许您注册设备的方向更改而不启用自动观看。

The above will allow you to register for orientation changes of the device without enabling the autorotate of your view.

在所有情况下在iOS中,当您添加一个观察者时,也会在适当的时候删除它(可能但不总是在视图出现/消失时)。您只能拥有观察/取消观察代码的对。如果你不这样做,应用程序将崩溃。选择观察/不观察的位置超出了本质量保证的范围。但是,你必须有一个unobserve来匹配上面的观察代码。

In all cases in iOS, when you add an observor, also remove it at appropriate times (possibly, but not always, when the view appears/disappears). You can only have "pairs" of observe/unobserve code. If you do not do this the app will crash. Choosing where to observe/unobserve is beyond the scope of this QA. However you must have an "unobserve" to match the "observe" code above.

这篇关于检测iOS UIDevice方向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆