ViewController的旋转一个举例

来源:互联网 发布:python xml dom 编辑:程序博客网 时间:2024/04/29 18:35


假设手机的四个方向分别是:1(Portrait),2(PortraitUpSideDown),3(LandscapeRight),4(LandscapeLeft)

假设一个工程有如下的界面旋转需求(支持iOS5.0及其以上版本需求)

只支持方向1,有如下A,B,C,D界面

支持方向1,方向3,方向4,有如下的界面:E



根据网上的资料和最新的相关文档,需要如下的实现:

在AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

    self.window = [[UIWindowalloc]initWithFrame:[[UIScreenmainScreen]bounds]];

    // Override point for customization after application launch.

    AViewController *vc = [[AViewControlleralloc]init];

    UINavigationController *nc = [[UINavigationControlleralloc]initWithRootViewController:vc];

    self.window.rootViewController = nc;

    [self.windowmakeKeyAndVisible];

    return YES;

}

因为给window的rootViewController是UINavigationController

要在iOS6.0中支持旋转,所以要实现如下的类别:

@implementation UINavigationController (Rotation_IOS6)

// iOS6.0

- (BOOL)shouldAutorotate

{

    returnself.topViewController.shouldAutorotate;

}


- (NSUInteger)supportedInterfaceOrientations

{

    returnself.topViewController.supportedInterfaceOrientations;

}

@end


因为ABCDE的ViewController都是同一种,假设ABCDE 都继承于BaseViewController,需要在BaseViewController,添加如下代码:

#pragma mark - befor iOS6.0

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation

{

    return interfaceOrientation == UIInterfaceOrientationPortrait;

}

#pragma mark - iOS6.0 and later

- (BOOL)shouldAutorotate

{

    return NO;

}

- (NSUInteger)supportedInterfaceOrientations {

    returnUIInterfaceOrientationPortrait;

}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation

{

    returnUIInterfaceOrientationPortrait;

}


ABCD界面已经满足需求了

因为E的旋转需求不一样,所以E中要重写上述的三个函数:

// before iOS6

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation

{

    return interfaceOrientation ==UIInterfaceOrientationLandscapeRight || interfaceOrientation ==UIInterfaceOrientationLandscapeLeft || interfaceOrientation ==UIInterfaceOrientationPortrait;

}

// iOS6 or later

- (NSUInteger)supportedInterfaceOrientations{

    returnUIInterfaceOrientationMaskAllButUpsideDown;

}


- (BOOL)shouldAutorotate

{

    return YES;

}


这样,无论ABCDE界面是push还是present都可以满足需求了