iOS将单个控制器设为横屏、页面横屏
2016-08-09 本文已影响314人
BYQiu
最近项目中拍照页面需要设置为横屏,需求如下
进入拍摄页面后将页面强制设为横屏,拍照结束后回复竖屏。
简述为:A->B(横屏)

1. 首先在AppDelegate中添加一个公开属性restrictRotation
并添加一个方法、该方法是是否允许屏幕转向
/** 允许转向 */
-(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
if(self.restrictRotation == YES)
return UIInterfaceOrientationMaskLandscapeRight;
// return UIInterfaceOrientationMaskLandscape;
else
return UIInterfaceOrientationMaskPortrait;
}
2. 在需要设置横屏的页面中添加下列方法
/**
* 设置屏幕旋转
*
* @param restriction yes or no
*/
- (void)restrictRotation:(BOOL) restriction {
AppDelegate* appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
appDelegate.restrictRotation = restriction;
}
在进入页面时允许屏幕旋转,并设置旋转的方向,代码如下
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self restrictRotation:YES];
NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight];
[[UIDevice currentDevice] setValue:value forKey:@"orientation"];
}
// 离开时禁止旋转并将屏幕方向设为竖屏
-(void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[self restrictRotation:NO];
NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
[[UIDevice currentDevice] setValue:value forKey:@"orientation"];
}
实现了将单个控制器设为横屏的功能。
但是,新的问题出现了:当B控制器返回A时,A控制器页变也为横屏
(需要将手机转向才能恢复)
解决办法很简单:
在A控制器的-(void)viewWillAppear:(BOOL)animated
方法中添加,再次设为竖屏即可
NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
[[UIDevice currentDevice] setValue:value forKey:@"orientation"];