iOS螢幕旋轉之Apple Document(蘋果文件翻譯)

weixin_34007291發表於2017-12-19

應用場景一:指定UIViewController支援旋轉或不旋轉

實現方法如下:

- (BOOL)shouldAutorotate {
    return YES;
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskPortrait;
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
    return UIInterfaceOrientationPortrait;
}

文件說明:
UIViewController物件屬性supportedInterfaceOrientations,返回所支援的橫豎屏的型別。

宣告

@property(nonatomic, readonly) UIInterfaceOrientationMask supportedInterfaceOrientations;

返回值

返回當前ViewController需要被支援的方向。這個值是一個列舉型別UIInterfaceOrientationMask,它包含了ViewController支援的旋轉方向。具體的取值如下:

typedef enum UIInterfaceOrientationMask : NSUInteger {
    UIInterfaceOrientationMaskPortrait = (1 << UIInterfaceOrientationPortrait),
    UIInterfaceOrientationMaskLandscapeLeft = (1 << UIInterfaceOrientationLandscapeLeft),
    UIInterfaceOrientationMaskLandscapeRight = (1 << UIInterfaceOrientationLandscapeRight),
    UIInterfaceOrientationMaskPortraitUpsideDown = (1 << UIInterfaceOrientationPortraitUpsideDown),
    UIInterfaceOrientationMaskLandscape = (UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight),
    UIInterfaceOrientationMaskAll = (UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight | UIInterfaceOrientationMaskPortraitUpsideDown),
    UIInterfaceOrientationMaskAllButUpsideDown = (UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight)
} UIInterfaceOrientationMask;

UIInterfaceOrientationMask簡介:該方法在iOS8之後被新增的,會讓你更得心應手的使用UITraitCollectionUITraitEnvironmentAPIs,在Size Class中也支援了這些屬性,也無需再依據UIInterfaceOrientation來確定你的ViewController所支援的方向。
在iOS8之前的版本中,你應該在supportedInterfaceOrientationsForWindow:方法中返回一個對應的值,來確定你ViewController的方向。這裡不展開講解。

注意

shouldAutorotate方法的返回值設為YES時,也就是當前控制器需要支援隨裝置旋轉,那麼當改變裝置的方向時,系統會在rootViewController,也就是keyWindowrootViewController中呼叫supportedInterfaceOrientations方法,舉個工程中常用的例子,如果當前工程的keyWindowrootViewControllerUITabBarController,那麼系統會在該ViewController中呼叫supportedInterfaceOrientations
在控制器中重寫這個方法來返回需要支援的方向,在iPad上的預設值是UIInterfaceOrientationMaskAll,在iPhone上預設值是UIInterfaceOrientationMaskAllButUpsideDown。控制器在該方法中返回的方向值,實際上是取決於Info.plist檔案或者appdelegateapplication:supportedInterfaceOrientationsForWindow:是否配置支援旋轉。

這裡再說一下,支援螢幕旋轉的info.plist檔案和appdelegate中的方法。
info.plist的配置實際上是在工程的target->general->Deployment Info 勾選Landscape LeftLandscape Right即可完成配置。
如果在Appdelegate使用程式碼配置如下:

//  如
- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{
    // iPad上需要支援所有方向
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        return UIInterfaceOrientationMaskAll;
    } else { /* iphone */
    // iPhone上只支援豎屏
        return UIInterfaceOrientationMaskPortrait ;
    }
}

相關文章