ios开发某个页面横不过来屏幕的时候
某一个页面需要横屏,其他的页面任然保持竖屏需要以下关键的几个步骤:
1.修改系统代理方法的返回值
1 -(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window { 2 //需要横屏的页面将此属性allowRotation修改为YES,竖屏的页面修改为NO 3 if (_allowRotation == YES) { 4 //页面仅支持横屏 5 return UIInterfaceOrientationMaskLandscapeRight; 6 }else{ 7 //页面仅支持竖屏 8 return UIInterfaceOrientationMaskPortrait; 9 10 } 11 }
2.在需要横屏的界面修改方法-(BOOL)shouldAutorotate的返回值为YES
- (BOOL)shouldAutorotate { #if 1 // 设置orientation来横屏竖屏(方式一) return YES; #else // 旋转式横屏竖屏(方式二) return NO; #endif }
3.代码实现将屏幕横过来
#pragma mark 横竖屏切换方法 - (void)interfaceOrientation:(UIInterfaceOrientation)orientation { /// 注释掉是因为包含私有API,不敢调用啊 // if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) { // // SEL selector = NSSelectorFromString(@"setOrientation:"); // NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]]; // [invocation setSelector:selector]; // [invocation setTarget:[UIDevice currentDevice]]; // int val = orientation; // // 从2开始是因为0 1 两个参数已经被selector和target占用 // [invocation setArgument:&val atIndex:2]; // [invocation invoke]; // } #if 1 // 设置orientation来横屏竖屏(方式一) NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown]; [[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"]; NSNumber *orientationTarget = [NSNumber numberWithInt:orientation]; [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"]; //刷新 [UIViewController attemptRotationToDeviceOrientation]; #else // 旋转式横屏竖屏(方式二) if (orientation == UIInterfaceOrientationLandscapeRight) { [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeRight animated:NO]; self.view.transform = CGAffineTransformMakeRotation(M_PI/2); self.view.frame = CGRectMake(0, 0, MainScreenHeight, MainScreenWidth); self.titleImage.frame = CGRectMake(0, 0, MainScreenHeight, MainScreenWidth); } if (orientation == UIInterfaceOrientationPortrait) { [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationPortrait animated:NO]; self.view.transform = CGAffineTransformMakeRotation(0); self.view.frame = CGRectMake(0, 0, MainScreenWidth, MainScreenHeight); self.titleImage.frame = CGRectMake(0, 0, MainScreenWidth, MainScreenHeight); } #endif }
4.UIViewController系统代理方法来检测屏幕旋转
#pragma mark 横竖屏切换或者进来横屏会触发的方法 -(void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator { [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> _Nonnull context) { //转屏前调入 -- 此处调用在viewDidLoad之前(重写init方法除外),可在此处做一些控件布局的横竖屏转换 completion:^(id<UIViewControllerTransitionCoordinatorContext> _Nonnull context) { //转屏后调入 -- 此处调用在viewDidLoad之后,可在此处做一些控件布局的横竖屏转换 }]; [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator]; }
经过上述4个步骤可完美实现转屏
by:初光夫