iOS开发中控制屏幕旋转的编写方法小结

2020-01-14 16:25:01于海丽
易采站长站为您分析iOS开发中控制屏幕旋转的编写方法小结,包括横竖屏切换时视图所出现的问题等经常需要注意的地方,需要的朋友可以参考下  

在iOS5.1 和 之前的版本中, 我们通常利用 shouldAutorotateToInterfaceOrientation: 来单独控制某个UIViewController的旋屏方向支持,比如:

复制代码
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation  
{  
    return (interfaceOrientation == UIInterfaceOrientationPortrait);  
}  

 

但是在iOS6中,这个方法被废弃了,使用无效。
shouldAutorotateToInterfaceOrientation:
Returns a Boolean value indicating whether the view controller supports the specified orientation. (Deprecated in iOS 6.0. Override the supportedInterfaceOrientations andpreferredInterfaceOrientationForPresentation methods instead.)

实践后会发现,通过supportedInterfaceOrientations的单独控制是无法锁定屏幕的。

复制代码
-(NSUInteger)supportedInterfaceOrientations  
{  
    return UIInterfaceOrientationMaskPortrait;  
}  

 

多次实验后总结出控制屏幕旋转支持方向的方法如下:
子类化UINavigationController,增加方法

复制代码
- (BOOL)shouldAutorotate  
{  
    return self.topViewController.shouldAutorotate;  
}  
  
- (NSUInteger)supportedInterfaceOrientations  
{  
    return self.topViewController.supportedInterfaceOrientations;  
}  
并且设定其为程序入口,或指定为 self.window.rootViewController
随后添加自己的view controller,如果想禁止某个view controller的旋屏:(支持全部版本的控制)
复制代码
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation  
{  
    return (interfaceOrientation == UIInterfaceOrientationPortrait);  
}  
  
-(BOOL)shouldAutorotate  
{  
    return NO;  
}  
  
-(NSUInteger)supportedInterfaceOrientations  
{  
    return UIInterfaceOrientationMaskPortrait;