您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 強制旋轉屏幕的兩種方法

編輯:iOS 開發綜合

方法一:透過狀態欄方向與 transform

利用狀態欄動畫的持續時間做一個過渡動畫,同時修改狀態欄方向並對 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 的寬高,來模擬橫竖屏切換。

方法二:調用私有 setOrientation:

非 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 可能導致審核被拒,正式項目中應謹慎評估。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved