Posted on

iOS6以上控制螢幕旋轉

一般的設定方式

//支援Xcode 4.5
- (NSUInteger) supportedInterfaceOrientations{
//僅正面
// return UIInterfaceOrientationMaskPortrait;

//支援縱向 (利用 | 設定多參數)
// return UIInterfaceOrientationMaskPortrait
// | UIInterfaceOrientationMaskPortraitUpsideDown;

//支援橫向
//UIInterfaceOrientationMaskLandscape: 支援按鈕在左、按鈕在右
// return UIInterfaceOrientationMaskLandscape;

//支援四個方向
return UIInterfaceOrientationMaskAll;

}

- (BOOL) shouldAutorotate {
return YES;
}

TabBarController設定方式

假使今天要控制所有畫面中,某些可支援旋轉,某些不行,
在有使用Navigation Controller和TabBarController的狀況時,
則需要這樣設定:

  1. 勾選支援畫面旋轉
    螢幕快照 2013-12-11 下午3.36.26
  2. 在AppDelegate加上這段程式碼
    - (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
    {
        NSUInteger orientations = UIInterfaceOrientationMaskAll;
    
        if (self.window.rootViewController) {
            UIViewController* presented = [[(UINavigationController *)self.window.rootViewController viewControllers] lastObject];
            orientations = [presented supportedInterfaceOrientations];
        }
        return orientations;
    }
  3. 在tabBarController裡加上
    -(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{
        return [self.selectedViewController shouldAutorotateToInterfaceOrientation:interfaceOrientation];
    }
    
    -(NSUInteger)supportedInterfaceOrientations{
        if (self.selectedViewController)
            return [self.selectedViewController supportedInterfaceOrientations];
    
        return UIInterfaceOrientationMaskPortrait;
    }
    
    -(BOOL)shouldAutorotate{
        return [self.selectedViewController shouldAutorotate];
    }
  4. 支援旋轉的子畫面加上
    - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
    {
        return (interfaceOrientation == UIInterfaceOrientationPortrait);
    }
    
    - (BOOL)shouldAutorotate
    {
        return NO;
    }
    
    - (NSUInteger)supportedInterfaceOrientations
    {
        return UIInterfaceOrientationMaskPortrait;
    }
  5. 要支援旋轉的子畫面加上
    - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
    {
        return YES;
    }
    
    - (BOOL)shouldAutorotate
    {
        return YES;
    }
    
    - (NSInteger)supportedInterfaceOrientations
    {
        return UIInterfaceOrientationMaskAllButUpsideDown;
    }

Navigation Controller設定方式

若要控制在Navigation Controller之下的單獨畫面是否支援旋轉,則需要在Controller裡加上這段

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return [self.visibleViewController shouldAutorotateToInterfaceOrientation:interfaceOrientation];
}

- (BOOL)shouldAutorotate {
    return [self.visibleViewController shouldAutorotate];
}

- (NSUInteger)supportedInterfaceOrientations {
    return [self.visibleViewController supportedInterfaceOrientations];
}