iOS 指定页面横竖屏切换及监听

3,187 阅读1分钟

在项目配置设置只支持竖屏

截屏2021-09-23 下午4.20.44.png

配置appdelegate

1.在appdelegate.h添加一个属性

@property (nonatomic, assign) BOOL allowRotation;

2.在appdelegate.m文件添加两个方法

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

// 支持旋转
- (BOOL)shouldAutorotate
{
    if (self.allowRotation) {
        return YES;
    }
    return NO;
}

3.在需要自动切换的ViewController中添加代码

- (void)viewDidLoad {
    [super viewDidLoad];
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    appDelegate.allowRotation = YES;
}

4.退出界面的时候回到竖屏,需要在控制器将要消失的时候添加代码

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    appDelegate.allowRotation = NO;
    if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
        [self interfaceOrientationPortrait:UIInterfaceOrientationPortrait];
    }
}

5.为了防止设备切换横竖屏不起作用

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

监听横竖屏切换

1.添加通知代码

[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
//这个通知会使iPhone横竖屏不受控制
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleDeviceOrientationDidChange:) name:UIDeviceOrientationDidChangeNotification object:nil]; 

2.通知类型处理

- (void)handleDeviceOrientationDidChange:(UIInterfaceOrientation)interfaceOrientation {
    UIDevice *device = [UIDevice currentDevice];
    switch (device.orientation) {
        case UIDeviceOrientationLandscapeLeft:
            NSLog(@"屏幕向左横置");
            break;

        case UIDeviceOrientationLandscapeRight:
            NSLog(@"屏幕向右橫置");
            break;

        case UIDeviceOrientationPortrait:
            NSLog(@"屏幕直立");
            break;

        case UIDeviceOrientationPortraitUpsideDown:
            NSLog(@"屏幕直立,上下顛倒");
            break;

        default:
            NSLog(@"无法辨识");
            break;
    }
}

提示:这个方法适合用于简单的场景,复杂的场景容易出现不可控的bug,慎用,感谢评论区 Yin€Q 告知