iOS16之前切換橫豎屏使用的是UIDevice
的setValue:forKey:
方法進行切換舌镶。但在iOS16后不再支持使用setValue
方法設(shè)置設(shè)備的方向髓需,建議替換為UIWindowScene
的requestGeometryUpdate
方法惶洲。
iOS16之前切換屏幕方法:
///豎屏
[[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIDeviceOrientationUnknown] forKey:@"orientation"];
[[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIDeviceOrientationPortrait] forKey:@"orientation"];
///橫屏
[[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIDeviceOrientationUnknown] forKey:@"orientation"];
[[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIDeviceOrientationLandscapeLeft] forKey:@"orientation"];
iOS16之后切換屏幕方法:
///豎屏
if (@available(iOS 16.0, *)) {
[self.navigationController setNeedsUpdateOfSupportedInterfaceOrientations];
NSArray *array = [[[UIApplication sharedApplication] connectedScenes] allObjects];
UIWindowScene *ws = (UIWindowScene *)array[0];
UIWindowSceneGeometryPreferencesIOS *geometryPreferences = [[UIWindowSceneGeometryPreferencesIOS alloc] init];
geometryPreferences.interfaceOrientations = UIInterfaceOrientationMaskPortrait;
[ws requestGeometryUpdateWithPreferences:geometryPreferences errorHandler:^(NSError * _Nonnull error) {
//業(yè)務(wù)代碼
}];
} else {
[[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIDeviceOrientationUnknown] forKey:@"orientation"];
[[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIDeviceOrientationPortrait] forKey:@"orientation"];
}
//橫屏
if (@available(iOS 16.0, *)) {
[self.navigationController setNeedsUpdateOfSupportedInterfaceOrientations];
NSArray *array = [[[UIApplication sharedApplication] connectedScenes] allObjects];
UIWindowScene *ws = (UIWindowScene *)array[0];
UIWindowSceneGeometryPreferencesIOS *geometryPreferences = [[UIWindowSceneGeometryPreferencesIOS alloc] init];
geometryPreferences.interfaceOrientations = UIInterfaceOrientationMaskLandscapeLeft;
[ws requestGeometryUpdateWithPreferences:geometryPreferences errorHandler:^(NSError * _Nonnull error) {
//業(yè)務(wù)代碼
}];
} else {
[[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIDeviceOrientationUnknown] forKey:@"orientation"];
[[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIDeviceOrientationLandscapeLeft] forKey:@"orientation"];
}
注意:[self.navigationController setNeedsUpdateOfSupportedInterfaceOrientations];這段代碼,需要寫在在轉(zhuǎn)屏的頁面合適位置,否則轉(zhuǎn)屏不起作用他爸,導(dǎo)致監(jiān)聽轉(zhuǎn)屏的方法
viewWillTransitionToSize: viewWillTransitionToSize
未被回調(diào)(自動轉(zhuǎn)屏?xí)r也不會回調(diào))咪橙。