如果在 info.plist 或 TARGETS --> General --> Deployment Info 里配置了支持橫屏的方向
且 手機(jī)有設(shè)置允許橫屏
此時(shí) App 頁(yè)面是跟隨手機(jī)設(shè)備的狀態(tài)而橫豎屏的
場(chǎng)景一恭应、如果我手機(jī)鎖定(如下圖)
則 此時(shí) App 頁(yè)面 只可以是豎屏的狀態(tài)
進(jìn)階版:如果已在 AppDelegate.m 里設(shè)置了禁止全局橫屏邢羔,特定頁(yè)面想要實(shí)現(xiàn)允許橫屏鸦采,如何操作荸百?
- (UIInterfaceOrientationMask)application:(UIApplication *)application
supportedInterfaceOrientationsForWindow:(UIWindow *)window {
return UIInterfaceOrientationMaskPortrait; // 默認(rèn)全局不支持橫屏
}
是需要修改代碼邏輯的囚似,具體操作如下:
1剩拢、在 AppDelegate.h 添加以下屬性:
// 是否 允許橫屏的 標(biāo)記
@property (nonatomic,assign)BOOL allowRotation;
2、在 Appdelegate.m 添加如下代碼:
- (UIInterfaceOrientationMask)application:(UIApplication *)application
supportedInterfaceOrientationsForWindow:(UIWindow *)window {
if (self.allowRotation) { // 如果設(shè)置了 allowRotation 屬性饶唤,支持全屏
return UIInterfaceOrientationMaskAll;
}
return UIInterfaceOrientationMaskPortrait; // 默認(rèn)全局不支持橫屏
}
3徐伐、在需要支持橫屏的界面改變 allowRotation 屬性
// 進(jìn)入全屏
- (void)enterViewAction {
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
appDelegate.allowRotation = YES;
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:UIInterfaceOrientationMaskLandscape];
[scene requestGeometryUpdateWithPreferences:geometryPreferences
errorHandler:^(NSError * _Nonnull error) {
NSLog(@"\n== Error 了: %@", error);
}];
} else {
}
}
// 退出全屏
- (void)quitViewAction {
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
appDelegate.allowRotation = NO;
if (@available(iOS 16.0, *)) {
// 同樣使用 requestGeometryUpdate 方法
} else {
// 強(qiáng)制歸正:
if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
SEL selector = NSSelectorFromString(@"setOrientation:");
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
[invocation setSelector:selector];
[invocation setTarget:[UIDevice currentDevice]];
int val =UIInterfaceOrientationPortrait;
[invocation setArgument:&val atIndex:2];
[invocation invoke];
}
}
}
4、在 viewWillAppear 和 viewWillDisappear 分別調(diào)用以上方法募狂,在該控制器下即可順利支持全屏 办素。
下面方法可能在 iOS 16.0 + 上無(wú)效,還需要進(jìn)一步測(cè)試祸穷。
// 進(jìn)入全屏
- (void)enterViewAction {
NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft];
[[UIDevice currentDevice] setValue:value forKey:@"orientation"];
}
// 退出全屏
- (void)quitViewAction {
NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
[[UIDevice currentDevice] setValue:value forKey:@"orientation"];
}