IOS6中橫屏的處理方法
IOS6以后,若想在項目中支持橫屏,我們首先需要在plist文件中添加支持橫屏的設置,否則有些代碼設置將會失效。
有來那個方式設置:
1、在pilist的Supported interface orientations 字段中添加
2、在Xcode的設置中勾選
現在我們來看決定屏幕方向的幾個函數:
在IOS6之前,我們只需通過一個函數
- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
return (toInterfaceOrientation == UIInterfaceOrientationLandscapeRight);
}
就可以支持指定控制器的旋轉。通過新的文檔,我們可以看到:
// Applications should use supportedInterfaceOrientations and/or shouldAutorotate.. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation NS_DEPRECATED_IOS(2_0, 6_0); //這個方法在6.0之后被標記為過時的
我們通過下面兩個方法來代替:
//是否允許屏幕旋轉
-(BOOL)shouldAutorotate{
return YES;
}
//支持的方向
- (NSUInteger)supportedInterfaceOrientations {
return UIInterfaceOrientationMaskLandscapeRight;
}
這是個枚舉
typedef NS_OPTIONS(NSUInteger, UIInterfaceOrientationMask) {
UIInterfaceOrientationMaskPortrait = (1 << UIInterfaceOrientationPortrait),
UIInterfaceOrientationMaskLandscapeLeft = (1 << UIInterfaceOrientationLandscapeLeft),
UIInterfaceOrientationMaskLandscapeRight = (1 << UIInterfaceOrientationLandscapeRight),
UIInterfaceOrientationMaskPortraitUpsideDown=(1 << UIInterfaceOrientationPortraitUpsideDown),
UIInterfaceOrientationMaskLandscape = (UIInterfaceOrientationMaskLandscapeLeft
| UIInterfaceOrientationMaskLandscapeRight),
UIInterfaceOrientationMaskAll = (UIInterfaceOrientationMaskPortrait
| UIInterfaceOrientationMaskLandscapeLeft
| UIInterfaceOrientationMaskLandscapeRight
| UIInterfaceOrientationMaskPortraitUpsideDown),
UIInterfaceOrientationMaskAllButUpsideDown = (UIInterfaceOrientationMaskPortrait
| UIInterfaceOrientationMaskLandscapeLeft
| UIInterfaceOrientationMaskLandscapeRight),
}; 通過這兩個函數,如果我們需要某個控制器強制方向,我們可以設置支持單一的方向,即可達到目的。
注意:
如果你們項目中的RootViewController是導航,你會發現,你在Push出來的視圖中添加剛才的代碼并沒有起作用,原因是導航,并沒有進行設置,我們創建一個文件,繼承于NavigationController。在里面重寫剛才的方法,這么做后,屏幕確實橫了過來,并且這個導航push的所有子界面都將橫屏,這也不是我們想要的效果。我們想自由的控制每個push出來的界面的屏幕方向,可以在導航里這么做:
-(BOOL)shouldAutorotate{
return [self.topViewController shouldAutorotate];
}
//支持的方向
- (NSUInteger)supportedInterfaceOrientations {
return [self.topViewController supportedInterfaceOrientations];;
} 我們還需要做一些處理,經過我的測試,導航必須在pop后才會重新調用這些函數,所以我的方法是這樣做:彈出一個中間控制器后再POP回來
@implementation ViewController2
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self.navigationController pushViewController:[[ViewController3 alloc]init] animated:YES];
}@implementation ViewController3
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self.navigationController popViewControllerAnimated:YES];
} 這樣做,我們就可以自由的控制每個視圖控制器的方向了。
同理,如果根視圖控制器是tabBar,則我們需要在tabBar中做操作。
如果我們大多是的視圖控制器都是一個方向的,只有偶爾的幾個會不同,這時候,我們其實可以采取presentationController的方式,然后直接在彈出的控制器中寫那兩個方法即可。這是最簡單的途徑了。