iOS 部分页面需要强制横屏
2018-10-25 本文已影响209人
半肥瘦
正在打包转测试,准备发布一个小版本。
------------------分割线------------------
产品:来 对接一个阅卷系统,一会给你拉到对接群里。
我:好久要,下个版本发吗?
产品:和这个版本一起发。
我:???(黑人问号)
产品:阅卷页面横屏,其他页面竖屏。
我:☺(尴尬又不失礼貌的笑容)
以下这种方法是不管手机有没有开启横竖屏锁定都会强制横屏
- 在Deployment Info 中把允许横屏打开(横向左右看自己)
【General】
-->【Deployment Info】
-->【Device Orientation】

- 在AppDelegate.h声明一个全局变量
/** 是否横屏 YES:横屏 NO:竖屏*/
@property (nonatomic,assign) BOOL allowAcrolls;
- 在AppDelegate.m中实现
/**
强制竖屏
@return 根据allowAcrolls字段来判断是否需要横屏
*/
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
if (self.allowAcrolls) {
return UIInterfaceOrientationMaskLandscapeLeft;
}
return UIInterfaceOrientationMaskPortrait;
}

- 在需要横屏的Controller调用下面这个方法
- (void)orientationToPortrait:(UIInterfaceOrientation)orientation {
SEL selector = NSSelectorFromString(@"setOrientation:");
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
[invocation setSelector:selector];
[invocation setTarget:[UIDevice currentDevice]];
int val = orientation;
[invocation setArgument:&val atIndex:2];
[invocation invoke];
}

Delegate的宏
#define CurrentAppDelegate ((AppDelegate *)[UIApplication sharedApplication].delegate)
在viewWillAppear
和viewWillDisappear
方法里控制横竖屏
- (void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
CurrentAppDelegate.allowAcrolls = NO;
[self orientationToPortrait:UIInterfaceOrientationPortrait];
}
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
CurrentAppDelegate.allowAcrolls = YES;
[self orientationToPortrait:UIInterfaceOrientationLandscapeLeft];
}