直接上代码
// 当前方向
UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
// 是否是横屏
BOOL isLandscape = (orientation == UIInterfaceOrientationLandscapeLeft || orientation == UIInterfaceOrientationLandscapeRight);
if (@available(iOS 16.0, *)) {
[self setNeedsUpdateOfSupportedInterfaceOrientations];
NSArray *array = [[[UIApplication sharedApplication] connectedScenes] allObjects];
UIWindowScene *scene = [array firstObject];
UIInterfaceOrientationMask orientation = isLandscape ? UIInterfaceOrientationMaskPortrait : UIInterfaceOrientationMaskLandscapeRight;
UIWindowSceneGeometryPreferencesIOS *geometryPreferencesIOS = [[UIWindowSceneGeometryPreferencesIOS alloc] initWithInterfaceOrientations:orientation];
[scene requestGeometryUpdateWithPreferences:geometryPreferencesIOS errorHandler:^(NSError * _Nonnull error) {
NSLog(@"强制%@错误:%@", isLandscape ? @"横屏" : @"竖屏", error);
}];
} else {
UIInterfaceOrientation orientationTarget = isLandscape ? UIInterfaceOrientationPortrait : UIInterfaceOrientationLandscapeRight;
[[UIDevice currentDevice] setValue:@(orientationTarget) forKey:@"orientation"];
}
//让屏幕方向与设备方向统一
[UIViewController attemptRotationToDeviceOrientation];
遇到的问题
真机测试横屏失效 Xcode Version 14.3.1 (14E300c)
ios15.3 连接真机无法在xcode调试模式下横屏,停止运行后,手动启动app,横屏可以实现。
知道原因导致的,欢迎交流指导。