iOS實現屏幕旋轉有兩種方式
1. 應用本身支持
2. 手動旋轉UIView (這種方式我沒找到旋轉 系統控件的方法 如:鍵盤、導航、UIAlertView)
如果你只是要把豎屏的播放器,做成支持橫屏的,沒有其他界面操作, 就可以考慮用第二種方式去做,比較簡單 ,不過要注意計算view Frame
這兩種方式看你具體的使用場景了,具體場景選擇合適的方式。
公司項目中有幾個界面要支持橫豎屏,(直播錄制界面、直播觀看界面、視頻回看界面)。 剛開始我想着用第二種方式去解決,但是我們視頻錄制、觀看界面有輸入框,需要調用鍵盤,沒找到可以手動旋轉鍵盤的方式,就改為讓應用本身支持屏幕旋轉。具體做法如下:
我們項目有一個 UITabBarController ,它有3個子CustomNavigationController, 我寫了一個
CustomNavigationController繼承自 UINavigationController
1. tabBarController 中
- (BOOL)shouldAutorotate{
return [self.selectedViewController shouldAutorotate];
}
//支持的方向
- (UIInterfaceOrientationMask)supportedInterfaceOrientations{
return [self.selectedViewController supportedInterfaceOrientations];
}
//初始方向
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
return UIInterfaceOrientationPortrait;
}
2. CustomNavigationController 重寫父類方法
- (BOOL)shouldAutorotate
{
return NO;
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskPortrait;
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
return UIInterfaceOrientationPortrait;
}
3. 我的支持屏幕旋轉的3個ViewController是presentViewController出來的; 在支持旋轉的界面加入以下代碼:
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
return toInterfaceOrientation != UIDeviceOrientationPortraitUpsideDown;
}
- (BOOL)shouldAutorotate
{
if (可以在此處做判斷,如果滿足條件就可以旋轉) {
return YES;
}
return NO;
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
if (可以在此處做判斷,如果滿足條件就支持豎屏) {
return UIInterfaceOrientationMaskPortrait;
}
return UIInterfaceOrientationMaskAllButUpsideDown;
}
還要做一件事---- 刷新UI布局;
4.
在ViewDidLoad中加入監聽屏幕旋轉的事件:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientChange:) name:UIDeviceOrientationDidChangeNotification object:nil];
在orientChange:方法中修改UI布局 ;
(注意: 看一下屏幕尺寸的變化 [[UIScreen mainScreen] bounds].size )
如果要控制CustomNavigationController push到的viewController的旋轉,那么就在CustomNavigationController里面區分是哪個viewController,以便單獨控制!
- (BOOL)shouldAutorotate
{
UIViewController *control = self.topViewController;
if ([control isKindOfClass:[@"支持旋轉的ViewController" class]]) {
return [control shouldAutorotate];
}
return YES;
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
UIViewController *control = self.topViewController;
if ([control isKindOfClass:[@"支持旋轉的ViewController" class]]) {
return [control supportedInterfaceOrientations];
}
return UIInterfaceOrientationMaskPortrait;
}