UIInterfaceOrientation和UIDeviceOrientation的区别

本文解析了UIInterfaceOrientation与UIDeviceOrientation的区别及其应用场景。指出两者在竖屏情况下的值相同,但在横屏时则相反。并强调了正确区分这两种类型的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


http://bukkake.iteye.com/blog/979515

UIInterfaceOrientation和UIDeviceOrientation的区别

 

UIInterfaceOrientation和UIDeviceOrientation长得是又长又像,长久时间我根本没有区分这两个类型,肯定也混用了无数,直到我现在处理的一个问题,明明是横/竖屏的情况,控件却是以竖/横的布局展示,而且我在模拟器上怎么都搞不出来,而测试稍微把机器转转圈就能重现这个现象。

 

那么定位的方向很明确,肯定是在willRotateToInterfaceOrientation之类的函数里咯。于是我看到了这样的代码

Objective-c代码   收藏代码
  1. - (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration  
  2. {  
  3. ...  
  4. CGRect rect;  
  5. if ( ([[UIDevice currentDevice] orientation] == UIDeviceOrientationPortrait) ||  
  6.     [[UIDevice currentDevice] orientation] == UIDeviceOrientationPortraitUpsideDown ) {  
  7.     rect = HRECT;  
  8.     }  
  9.     else {  
  10.     rect = VRECT;  
  11.     }  
  12. [alertView setFrame:rect];  
  13. ...  
  14. }  

 乍一看其实也没什么,竖屏的时候就用竖屏的frame布局,此外就用横屏的布局,这没有什么问题啊。然后我抱着试试看的心里,跳到了UIDeviceOrientationPortrait的定义,突然发现这个枚举值竟然有七个,除了一个unknown之外,还有上下,左右,翻盖这六种。这个时候我才注意到,程序里用的类型是UIDeviceOrientation,而切换横竖屏的函数的参数实际上是UIInterfaceOrientation,这可把我吓出一身冷汗,以前从来没注意过,都是随便找之前写的代码抄过来判断横竖屏的,那么一旦误用会有多少问题啊。于是我找了一下资料,来源主要是这里 。

 

而且两者除了区别还有联系,打开头文件大家也可以看到

Objective-c代码   收藏代码
  1. typedef enum {  
  2.     UIInterfaceOrientationPortrait           = UIDeviceOrientationPortrait,  
  3.     UIInterfaceOrientationPortraitUpsideDown = UIDeviceOrientationPortraitUpsideDown,  
  4.     UIInterfaceOrientationLandscapeLeft      = UIDeviceOrientationLandscapeRight,  
  5.     UIInterfaceOrientationLandscapeRight     = UIDeviceOrientationLandscapeLeft  
  6. } UIInterfaceOrientation;  

 也就是意味着竖屏的时候两者的值是完全对应,而横屏的时候相反的对应关系则反应了向左摇的时候,设备正好是朝着右边的,也有人说HOME在右边。

 

还有就是UIDeviceOrientation一定会根据设备当前的位置朝向而改变,但UIInterfaceOrientation则未必,比如你根本不让设备转动的话,那么怎么都是获得到UIInterfaceOrientationPortrait这个值的。

 

如果你的设备支持摇动,那么直接在willRotateToInterfaceOrientation的函数里根据参数即可获得当前状态,而万一遇到新界面没有获得摇动消息却要确定当前状态,那就用[UIApplication sharedApplication].statusBarOrientation写在viewWillAppear之类的函数里。当然最方便最合适的做法是用UIInterfaceOrientationIsPortrait和UIInterfaceOrientationIsLandscape两个预设宏。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值