项目中写好了横屏适配,一直也忘了整理出来,今天正好周五有空记录一下
先在AppDelegate文件中添加
//AppDelegate.h
@property (nonatomic, assign) BOOL screenOrientations; /**< 是否是横屏 */
- (void)setScreenOrientations:(BOOL)screenOrientations;
//AppDelegate.m
- (void)setScreenOrientations:(BOOL)screenOrientations {
_screenOrientations = screenOrientations;
[self application:[UIApplication sharedApplication] supportedInterfaceOrientationsForWindow:nil];
}
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
if (self.screenOrientations) {
return UIInterfaceOrientationMaskAll;
}
return UIInterfaceOrientationMaskPortrait;
}
去要横屏的页面加入下面代码
//viewWillDisappear方法添加
[self.appDelegate setscreenOrientations:NO];
//viewDidLoad方法添加
if (@available(iOS 16.0, *)) {
[self.appDelegate setscreenOrientations:YES];
}
/// 切换设备方向
- (void)p_switchOrientationWithLaunchScreen{
if (@available(iOS 16.0, *)) {
// setNeedsUpdateOfSupportedInterfaceOrientations 方法是 UIViewController 的方法,所以这个操作最好是放在控制器中去操作
[self setNeedsUpdateOfSupportedInterfaceOrientations];
NSArray *array = [[[UIApplication sharedApplication] connectedScenes] allObjects];
UIWindowScene *scene = [array firstObject];
// 屏幕方向
UIInterfaceOrientationMask orientation = UIInterfaceOrientationMaskLandscapeRight;
UIWindowSceneGeometryPreferencesIOS *geometryPreferencesIOS = [[UIWindowSceneGeometryPreferencesIOS alloc] initWithInterfaceOrientations:orientation];
// 开始切换
[scene requestGeometryUpdateWithPreferences:geometryPreferencesIOS errorHandler:^(NSError * _Nonnull error) {
}];
} else {
[self swichOldOrientation:UIInterfaceOrientationLandscapeRight];
}
}
/// iOS16 之前进行横竖屏切换方式
- (void)swichOldOrientation:(UIInterfaceOrientation)interfaceOrientation {
NSNumber *orientationTarget = [NSNumber numberWithInteger:interfaceOrientation];
[[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
}
在我的swift项目中貌似没啥影响,如果下面代码不行,可以自行将上面的oc代码转成swift
/// 屏幕方向
override open var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .landscapeRight
}