iOS点点滴滴iOS自鉴

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

2018-08-23  本文已影响0人  丁桥人在外地

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

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];
    
}

希望对你有帮助 ,若有疑问可联系675399100

上一篇下一篇

猜你喜欢

热点阅读