この記事では、自動回転方向の動的制御 (1 ~ 3)、画面方向の手動回転 (4 番目)、vc のビューを回転することによる画面方向の疑似回転について説明します。
1. 回転するように vc を構成する
方向を設定する必要がある vc でこの関数をオーバーライドします。
- (BOOL)shouldAutorotate {
return YES;
}
2. vc が回転できる方向
方向を設定する必要がある vc でこの関数を上書きすると、戻り値を動的に変更して、画面の回転方向を手動で制御できます。
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
return UIInterfaceOrientationMaskAll;
}
3. アプリケーションの方向を設定する必要がある場合があります
AppDelegate でこの関数をオーバーライドすると、戻り値を動的に変更して、画面の回転方向を手動で制御できます。
- (UIInterfaceOrientationMask) application:(UIApplication *)application
supportedInterfaceOrientationsForWindow:(UIWindow *)window {
return UIInterfaceOrientationMaskAll;
}
上記の手順をすべて設定すると、実際に画面を自動的に回転させることができ、回転できる方向は返される値になります。
3. 手動回転方向
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
UIInterfaceOrientationMask orientationMask = UIInterfaceOrientationMaskLandscapeRight;
UIDeviceOrientation deviceOrientation = UIDeviceOrientationLandscapeRight;
if (@available(iOS 16.0, *)) {
[self setNeedsUpdateOfSupportedInterfaceOrientations];
NSArray *array = [[[UIApplication sharedApplication] connectedScenes] allObjects];
UIWindowScene *scene = [array firstObject];
UIWindowSceneGeometryPreferencesIOS *geometryPreferencesIOS = [[UIWindowSceneGeometryPreferencesIOS alloc] initWithInterfaceOrientations:orientationMask];
[scene requestGeometryUpdateWithPreferences:geometryPreferencesIOS
errorHandler:^(NSError *_Nonnull error) {
NSLog(@"屏幕旋转 错误:%@", error);
}];
} else {
[[UIDevice currentDevice] setValue:@(deviceOrientation) forKey:@"orientation"];
[UIViewController attemptRotationToDeviceOrientation];
}
[[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];
注意点は手動で回転させる場合はvcサポート方向とアプリケーションリターン方向の値を回転できるように修正する必要があることです。すべての向きを使用しない理由は、自動回転が邪魔になるためで、たとえば、画面が物理的に垂直である場合、自動回転は垂直に回転し、手動回転が失敗する可能性があります。
4. ビューを回転する
如果不想像上面那样麻烦控制,直接旋转View也是一个旋转屏幕的方法。但是这个方法有个问题是,设备方向没有真正旋转,所以状态栏方向可能是错的,下拉锁屏方向看起来也会有些异常。
- (BOOL)prefersStatusBarHidden {
return _isRight;
}
-(void)changeOrientationRight {
//设备方向没有转动,所以状态栏方向是错的,要隐藏
_isRight = YES;
[self setNeedsStatusBarAppearanceUpdate];
self.view.transform = CGAffineTransformMakeRotation(M_PI/2);
CGSize size = UIScreen.mainScreen.bounds.size;
self.view.bounds = CGRectMake(0, 0, size.height, size.width);
}