ios屏幕的旋转,Device Orientation

屏幕旋转,我的理解是ios设备根据重力感应改变屏幕的方向。那么如何在屏幕转动后变换UI?或则保持原样呢?

ios设备支持4个方向,UIInterfaceOrientationPortrait,UIInterfaceOrientationPortraitUpsideDown,UIInterfaceOrientationLandscapeLeft

UIInterfaceOrientationLandscapeRight。

设置屏幕旋转支持方向的方法有2个

1. 在xcode中选择相应的项目,然后在右边设置页面中选择General,最后在Device Orientation可以选择支持的旋转方向,如下图


2. 另一个方法

IOS 6.0以上

当设备发生旋转时会调用主window的rootViewController或最顶层的ViewController的shouldAutorotate询问是否可以自动旋转,当允许旋转后会再调用supportedInterfaceOrientation。

UIViewController * _controller = [[UIViewController alloc] init];
CustomNav * _nav = [[CustomNav alloc] initWithRootViewController:_controller];
[self.window setRootViewController:_nav];


@implementation CustomNav : UINavigationController
- (BOOL)shouldAutorotate
{
    return [self.topViewController shouldAutorotate];
}

- (NSUInteger)supportedInterfaceOrientations
{
    return [self.topViewController supportedInterfaceOrientations];
}
@end

如果想让某几个页面不转动或只支持特定的方向转动可以重写响应UIViewController的shouldAutoroate和supportedInterfaceOrientations方法

IOS 6.0 以下,需重写shouldAutorotateToInterfaceOrientation:UIInterfaceOrientation

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    if ( toInterfaceOrientation == UIDeviceOrientationPortrait ) {
        return YES;
    } else {
        return NO;
    }
}

2种方法可以结合使用,但supportedInterfaceOrientations返回值必须要包含object中设置的值,否则会引起crash。

另外如果将UINavigationController做为rootViewController,在pop时会重新调用shouldAutoroate和supportedInterfaceOrientations,小伙伴们看看是否可以利用一下。


还可以通过监听的方式来获知屏幕旋转,但不能控制旋转。

首先必须设置window的rootViewController,否则无法监听到屏幕旋转的消息

[self.window setRootViewController:_nav];
    
[self.window addSubview:_nav.view];
    
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(receiverNotification)
                                             name:UIDeviceOrientationDidChangeNotification
                                           object:nil];


当然还可以使用transform的方式来直接旋转UIVIew或window, 但我认为这些并不算屏幕旋转的范畴,可以在以后讨论动画的时候再说。



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值