利用狀態欄動畫的持續時間做一個過渡動畫,同時修改狀態欄方向並對 view 施加旋轉變換,達到強制旋轉的效果:
// 狀態欄動畫持續時間
CGFloat duration = [UIApplication sharedApplication].statusBarOrientationAnimationDuration;
[UIView animateWithDuration:duration animations:^{
// 修改狀態欄方向及 view 方向,進而強制旋轉屏幕
[[UIApplication sharedApplication] setStatusBarOrientation:_bottomView.landscapeModel ? UIInterfaceOrientationLandscapeRight : UIInterfaceOrientationPortrait];
self.navigationController.view.transform = _bottomView.landscapeModel ? CGAffineTransformMakeRotation(M_PI_2) : CGAffineTransformIdentity;
self.navigationController.view.bounds = CGRectMake(self.navigationController.view.bounds.origin.x, self.navigationController.view.bounds.origin.y, self.view.frame.size.height, self.view.frame.size.width);
}];
這個方法透過旋轉整個 navigationController 的 view,並交換 bounds 的寬高,來模擬橫竖屏切換。
非 ARC 環境下:
if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
[[UIDevice currentDevice] performSelector:@selector(setOrientation:) withObject:(id)UIInterfaceOrientationLandscapeRight];
}
ARC 環境下,由於編譯器對 performSelector 的限制,改用 NSInvocation 來實現:
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 = UIInterfaceOrientationLandscapeRight;
[invocation setArgument:&val atIndex:2];
[invocation invoke];
}
需要提醒的是,setOrientation: 屬於私有 API,若打算提交到 App Store,使用私有 API 可能導致審核被拒,正式項目中應謹慎評估。