iOS项目页面横屏的实现

213 阅读1分钟

背景:iOS端页面横屏的实现经历多次api变化,并且横屏相关的api较多,实现起来不知道哪些是必须要用的哪些不需要。要真正自由实现某些页面横屏显示某些页面竖屏显示有些变化,暂做记录。

实现:目前最简单灵活有效的实现是需要的时候重调用application:supportedInterfaceOrientationsForWindow:方法,在方法内return方向。具体实现可以在appdelegate添加一个属性控制如是否横屏 @property (nonatomic, assign, getter=isLaunchScreen) BOOL launchScreen; 然后实现set方法

  • (void)setLaunchScreen:(BOOL)launchScreen {

    _launchScreen = launchScreen;

    [self application:[UIApplication sharedApplication] supportedInterfaceOrientationsForWindow:self.window];

}

在set方法里面调用application:supportedInterfaceOrientationsForWindow:方法 同时在application:supportedInterfaceOrientationsForWindow:方法里面判断是否横屏

  • (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {

    if (_launchScreen) {

        return UIInterfaceOrientationMaskLandscapeLeft;

    }

    return UIInterfaceOrientationMaskAll;

}

最后就是在需要的地方调用了,如

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

    if (orientation == UIInterfaceOrientationMaskLandscape) {

        // 全屏操作

        appdelegate.launchScreen = YES;

    } else {

        // 退出全屏操作

        appdelegate.launchScreen = NO;

    }

另外如果不能获取当前delegate,也可以发通知,在delegate接收到通知之后执行application:supportedInterfaceOrientationsForWindow:方法。

其他:此外还有一些其他一些设置方向的方式,实测不是很好用,要么是新版本才支持,要么是只有老版本支持。

if (@available(iOS 16.0, *)) {

        [self setNeedsUpdateOfSupportedInterfaceOrientations];

        [self.navigationController setNeedsUpdateOfSupportedInterfaceOrientations];

        NSArray *array = [[[UIApplication sharedApplication] connectedScenes] allObjects];

        UIWindowScene *scene = (UIWindowScene *)array[0];

        UIWindowSceneGeometryPreferencesIOS *geometryPreferences = [[UIWindowSceneGeometryPreferencesIOS alloc] initWithInterfaceOrientations:orientation];

        [scene requestGeometryUpdateWithPreferences:geometryPreferences

                                       errorHandler:^(NSError * _Nonnull error) {

            NSLog(@"wuwuFQ:%@", error);

        }];

    } else {

        [[UIDevice currentDevice] setValue:[NSNumber   numberWithInteger:UIDeviceOrientationUnknown] forKey:@"orientation"];

        [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIDeviceOrientationLandscapeRight] forKey:@"orientation"];

    }