iOS: Support Rotation

来源:互联网 发布:hp网络打印机安装 编辑:程序博客网 时间:2024/05/22 12:01


支持旋转很简单,只需要在支持旋转的view controller里重写shouldAutorotateToInterfaceOrientation即可

注意:在你的project的target里有一个"Supported Device Orientations" option,该option只是setting the UISupportedInterfaceOrientations key in Info.plist,它只是用于决定在launch app时,应该使用什么Orientation,而不是指你的app支持哪几个orientation

例如,如果你设置"Supported Device Orientations" option为landscape left and landscape right,那么在启动app时,就一定是横向的。但当进入到app之后,如果重写的shouldAutorotateToInterfaceOrientation支持portrait,还是一样可以使app竖屏。


代码例子:

1. 当前view除了portrait upsidedown之外,其他都支持

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);}

2. 当前view只支持横屏

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{    return (interfaceOrientation != UIInterfaceOrientationPortrait && interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);    }


iPhone版的youtube app,在video list view一定是竖屏的,进入到video view后一开始一定是横屏(即使你的iphone是打竖的)。你只有先把iphone打横,然后打竖,才能使video view打竖屏。这个效果怎么做?

旧的ios version是通过[[UIDevice currentDevice] setOrientation来设置orientation。但iOS 5之后就把该method变成private了。而且var orientation也变成只读的。

@property (nonatomic, readonly) UIDeviceOrientation orientation

那么我们只能在shouldAutorotateToInterfaceOrientation方法里想办法:在view controller定义一个bool flag var "isEnablePortrait", init value is "No",然后使用下列代码:

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{    NSLog(@"rotate");        if(isSupportPortrait){        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);                    } else {        return (interfaceOrientation != UIInterfaceOrientationPortrait && interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);    }    }

那么当某个动作完成后(例如load data complete),就把isEnablePortrait=Yes,使其可以打竖。


旋转之后如何调整控件的位置和大小?

对于一个简单的view来说,只需要设置每个控件的autosizing属性即可。该属性在xcode里有图例,容易明白。

参考文档: http://www.game798.com/youxijiaocheng/youxichengxujiaocheng/042526312012_3.html



但对于一些稍微复杂点的,例如竖屏是每行显示3个icon,横屏每行显示4个icon,应该写代码实现。


基本思路:尽可能的使用autosizing。即使你需要使用写代码来实现,也尽量先使用autosizing来减少代码量。即使用autosizing + 代码结合来达到目的。


写代码来调整旋转后的控件有2种方式 : 

1. 旋转时逐个逐个控件调整位置和大小:通过重写willRotateToInterfaceOrientation:toInterfaceOrientation方法,在该方法里根据orientation来设置控件的frame (通过CGRectMake方法) 。

缺点:你需要记下每一个控件分别在横屏和竖屏的x,y, width, height。麻烦啊。。。

优点:不用创建2个view xib


2. 一个view controller对应2个view xib,一个view for 横屏,另一个view for 竖屏。在willRotateToInterfaceOrientation:toInterfaceOrientation方法根据orientation来设置self.view是竖屏的view还是横屏的view

优点:不用记住每个控件的x,y, width, height。

缺点:在view controller里要对2个view xib里的控件以及该view分别进行outlet connection。(IBAction可以share,但IBoutlet不能share)




原创粉丝点击