iOS 指定页面支持横竖屏切换

项目要在配置里只支持竖屏

1.首先在appdelgate里添加一个属性

@property(nonatomic, assign) BOOL allowRotation; 

2.在.m文件中添加一下两个方法

- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
     
    if (self.allowRotation == 1) {
     
        return UIInterfaceOrientationMaskAll;
    }else{
     
        return (UIInterfaceOrientationMaskPortrait);
    }
} 

// 支持设备自动旋转
- (BOOL)shouldAutorotate
{
     
    if (self.allowRotation == 1) {
     
        return YES;
    }
    return NO;
}

3.在想要支持横屏的控制器中添加一下代码

AppDelegate  *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
appDelegate.allowRotation = 1;

这样就可以实现在指定界面进行横竖屏切换了,退出当前界面的时候 肯定要回到竖屏 , 此时在控制器将要消失的时候添加代码

AppDelegate  *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;

appDelegate.allowRotation = 0;

if ([[UIDevice currentDevice]respondsToSelector:@selector(setOrientation:)]) {
     
    [self orientationToPortrait:UIInterfaceOrientationPortrait];
}

还要自己写一个方法在当前的控制器页面的.m文件里

// 防止更改设备的横竖屏不起作用
-(void)orientationToPortrait:(UIInterfaceOrientation)orientation{
     
    SEL seletor = NSSelectorFromString(@"setOrientation:");
    NSInvocation *invocatino = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:seletor]];
    [invocatino setSelector:seletor];
    [invocatino setTarget:[UIDevice currentDevice]];
    int val = orientation;
    [invocatino setArgument:&val atIndex:2];
    [invocatino invoke];
    
}

作者:丁桥人在外地
链接:https://www.jianshu.com/p/6eee94ebb861
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

你可能感兴趣的:(iOS,横竖屏)