原代碼是這樣:
- (void)setInterfaceOrientation:(UIInterfaceOrientation)orientation {
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 = orientation;
[invocation setArgument:&val atIndex:2];
[invocation invoke];
}
當(dāng)需要強(qiáng)制旋轉(zhuǎn)屏幕時(shí),傳入目標(biāo)的 orientation 達(dá)到強(qiáng)制旋轉(zhuǎn)屏幕的目的。但是,如題所示,在 iOS 16 中,通過(guò)設(shè)置設(shè)置 UIDevice.orientation 來(lái)強(qiáng)制旋轉(zhuǎn)屏幕的方向已不再被支持。
根據(jù)錯(cuò)誤提示,需要使用 UIWindowScene.requestGeometryUpdate(_:) 方法來(lái)實(shí)現(xiàn)。于是修改后的代碼如下:
///強(qiáng)制轉(zhuǎn)換屏幕方向
- (void)ll_interfaceOrientation:(UIInterfaceOrientation)orientation {
if(@available(iOS 16.0, *)) {
UIScene *windowScene = [[[UIApplication sharedApplication] connectedScenes] anyObject];
UIWindowSceneGeometryPreferencesIOS *preferences = nil;
if (orientation == UIInterfaceOrientationLandscapeRight || (orientation == UIInterfaceOrientationLandscapeLeft)) {
preferences = [[UIWindowSceneGeometryPreferencesIOS alloc] initWithInterfaceOrientations:UIInterfaceOrientationMaskLandscape];
}else {
preferences = [[UIWindowSceneGeometryPreferencesIOS alloc] initWithInterfaceOrientations:UIInterfaceOrientationMaskPortrait];
}
[(UIWindowScene *)windowScene requestGeometryUpdateWithPreferences:preferences errorHandler:^(NSError * _Nonnull error) {
}];
}else {
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 = orientation;
[invocation setArgument:&val atIndex:2];
[invocation invoke];
}
}
}