以强制竖屏为例,强制横屏同理。
如果要全部竖屏,直接在Info.plist中设置即可。这里讨论的是全局可转屏,但是某些页面只能竖屏。
要做到强制竖屏,有两个要点。
1. 禁止转屏
2. 竖屏进入页面。
仅仅设置禁止转屏还不能保证一定是竖屏的。因为如果从横屏的状态进入当前页面的的话,当前页面就会也是横屏的。所以要强制竖屏,除了禁止转屏,还要做到竖屏进入页面。
禁止转屏
禁止转屏可以通过重写shouldAutoRotate实现。iOS7中,需要增加UINavigationController的支持。
具体参考iOS7中禁止某些页面转屏
实现扩展
#import "UINavigationController+Autorotate.h"
@implementation UINavigationController (Autorotate)
-(BOOL)shouldAutorotate {
return [[self.viewControllers lastObject] shouldAutorotate];
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
return [[self.viewControllers lastObject] preferredInterfaceOrientationForPresentation];
}
-(NSUInteger)supportedInterfaceOrientations{
return [[self.viewControllers lastObject] supportedInterfaceOrientations];
}
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation{
return [[self.viewControllers lastObject] shouldAutorotateToInterfaceOrientation:toInterfaceOrientation];
}
@end
竖屏进入页面
要做到竖屏进入页面,根据网上的资料,一个是调用setOrientation,一个是设置transform。
1. transform的方式我没有实现。
转屏没有问题,但是因为项目用的是AutoLayout,所以修改view的bounds的时候,不起作用。没有找到解决办法。
2. setOrientation一开始不起作用。因为设置了shouldAutoRotate为NO。所以横屏启动的时候,也没法转成竖屏。
修改下
-(BOOL)shouldAutorotate{
return UIInterfaceOrientationIsLandscape(self.interfaceOrientation);
}
这样就是横屏可以转,竖屏不能转。
也就能保证横屏启动的时候,可以转成竖屏,但是转成竖屏之后,就不再能转成横屏。(强制横屏时,相反地,只允许竖屏转)
强制转屏的代码:
- (void)viewDidLoad
{
[super viewDidLoad];
if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
SEL selector = NSSelectorFromString(@"setOrientation:");
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
[invocation setSelector:selector];
[invocation setTarget:[UIDevice currentDevice]];
int val = UIInterfaceOrientationPortrait;
[invocation setArgument:&val atIndex:2];
[invocation invoke];
}
//...
}