用代码实现在某页面强制横屏。
在AppDelegate.h中定义一个属性,如下:
//是否允许转向
@property(nonatomic,assign)BOOL allowRotation;
AppDelegate.m中实现横屏或竖屏的设置:
// 如果属性值为YES,仅允许屏幕向左旋转,否则仅允许竖屏。
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
if (self.allowRotation == YES) {
// 横屏
return UIInterfaceOrientationMaskLandscape;
} else {
// 竖屏
return (UIInterfaceOrientationMaskPortrait);
}
}
在UIDevice分类中实现强制转屏,如下:
// 输入要强制转屏的方向
//@param interfaceOrientation 转屏的方向
+ (void)deviceMandatoryLandscapeWithNewOrientation:(UIInterfaceOrientation)interfaceOrientation {
NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];
[[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"];
// 将输入的转屏方向(枚举)转换成Int类型
int orientation = (int)interfaceOrientation;
// 对象包装
NSNumber *orientationTarget = [NSNumber numberWithInt:orientation];
// 实现横竖屏旋转
[[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
}
在需要旋转屏幕的地方调用如下方法:
AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
// 打开横屏开关
appDelegate.allowRotation = YES;
// 调用转屏代码
[UIDevice deviceMandatoryLandscapeWithNewOrientation:UIInterfaceOrientationLandscapeRight];
在返回到上一个页面的时候,如果需要保持原来的竖屏,那么就应该实现对应的方法即可:
AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
// 关闭横屏仅允许竖屏
appDelegate.allowRotation = NO;
// 切换到竖屏
[UIDevice deviceMandatoryLandscapeWithNewOrientation:UIInterfaceOrientationPortrait];
[self.navigationController popViewControllerAnimated:YES];