本文主要介绍屏幕旋转的使用步骤, 以及一些注意事项.
一, 设备方向(UIDevice) 设备方向通过加速计获取, 如果有获取设备方向, 一定要先开启设备旋转的通知, 否则一致是 unkown 开启设备方向通知方法: if (![[UIDevice currentDevice] isGeneratingDeviceOrientationNotifications]) { [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications]; } 不需要监听的时候请关闭
二, 界面方向(statusBarOrientation)
1 |
|
模态强制横屏的方法:
- (BOOL)shouldAutorotate{ return NO; }
- (UIInterfaceOrientationMask)supportedInterfaceOrientations{ return UIInterfaceOrientationMaskLandscapeLeft; }
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{ return UIInterfaceOrientationLandscapeLeft; }
push强制横屏的方法:
- (void)viewWillAppear:(BOOL)animated{ [super viewWillAppear:animated]; [self setInterfaceOrientation:UIInterfaceOrientationLandscapeLeft];
}
- (BOOL)shouldAutorotate{ //必须返回yes return YES; }
- (UIInterfaceOrientationMask)supportedInterfaceOrientations{ return UIInterfaceOrientationMaskLandscapeLeft; }
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{ return UIInterfaceOrientationLandscapeLeft; }
//必须实现如下方法, 可以在基类实现
-
(void)setInterfaceOrientation:(UIInterfaceOrientation)orientation { if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) { SEL selector = NSSelectorFromString(@”setOrientation:”); NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]]; [invocation setSelector:selector]; [invocation setTarget:[UIDevice currentDevice]]; [invocation setArgument:&orientation atIndex:2]; [invocation invoke];
} }
如果跟控制是tabbar 将屏幕旋转交由选中控制器去实现 /** 是否支持自动旋转屏幕 */
- (BOOL)shouldAutorotate{ return [self.selectedViewController shouldAutorotate]; }
/** 屏幕旋转支持的方向 */
- (UIInterfaceOrientationMask)supportedInterfaceOrientations{ return [self.selectedViewController supportedInterfaceOrientations]; }
/** 模态出的控制器优先支持的屏幕方向
*/
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{ return [self.selectedViewController preferredInterfaceOrientationForPresentation]; }
如果跟控制器是navigation, 将旋转交由栈顶控制器实现 /将屏幕旋转交由导航控制器的栈顶控制器管理
- (BOOL)shouldAutorotate{ return [self.viewControllers.lastObject shouldAutorotate]; }
- (UIInterfaceOrientationMask)supportedInterfaceOrientations{ return [self.viewControllers.lastObject supportedInterfaceOrientations]; }
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{ return [self.viewControllers.lastObject preferredInterfaceOrientationForPresentation]; }
注意事项: 1, 屏幕旋转取消交互 2,屏幕旋转重新刷新界面, 如果是tableView, 不reloadData可能cell显示不全