公司App里面有个需求,即所有界面都是竖屏,且不允许横屏切换,唯独有一个播放视频的界面允许横屏,大家都知道视频播放适配最大的播放屏幕那样是最好的。从网上多方查找资料,查到了这么一篇文章:
[http://simayang.com/archives/405.html]
(IOS横竖屏控制与事件处理)
最终,根据此需求处理如下: 首先,确保App本身应该允许转屏切换:
再次,我的App里面UITabBarController是主控制器,所以首先创建一个UITabBarController的子类,并设定允许转屏:
#pragma mark 转屏方法重写
-(UIInterfaceOrientationMask)supportedInterfaceOrientations
{
return [self.viewControllers.firstObject supportedInterfaceOrientations];
}
-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
return [self.viewControllers.firstObject preferredInterfaceOrientationForPresentation];
}
-(BOOL)shouldAutorotate{
return self.viewControllers.firstObject.shouldAutorotate;
}
接着,tabbarController里面每个子控制器都是UINavigationController进行界面push切换的,所以首先创建一个UINavigationController的子类,并设定允许转屏:
#pragma mark 转屏方法重写
-(UIInterfaceOrientationMask)supportedInterfaceOrientations
{
return [self.viewControllers.lastObject supportedInterfaceOrientations];
}
-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
return [self.viewControllers.lastObject preferredInterfaceOrientationForPresentation];
}
-(BOOL)shouldAutorotate{
return self.visibleViewController.shouldAutorotate;
}
最后,在你不想转屏切换的ViewController上重写以下方法:
#pragma mark 转屏方法 不允许转屏
-(UIInterfaceOrientationMask)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskPortrait ;
}
- (BOOL)shouldAutorotate
{
return NO;
}
-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
return UIInterfaceOrientationPortrait;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation{
return NO;
}
在你想转屏切换的ViewController上可以照这样重写(允许左右横屏以及竖屏):
- (BOOL)shouldAutorotate {
return YES;
}
-(UIInterfaceOrientationMask)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskAll;
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
return UIInterfaceOrientationPortrait;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
另外,在ViewController中对于转屏事件可以参见下面的方法进行捕获:
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id)coordinator
{
[super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
[coordinator animateAlongsideTransition:^(id context) {
//计算旋转之后的宽度并赋值
CGSize screen = [UIScreen mainScreen].bounds.size;
//界面处理逻辑
self.lineChartView.frame = CGRectMake(0, 30, screen.width, 200.0);
//动画播放完成之后
if(screen.width > screen.height){
NSLog(@"横屏");
}else{
NSLog(@"竖屏");
}
} completion:^(id context) {
NSLog(@"动画播放完之后处理");
}];
}
区分当前屏幕是否为横竖屏的状态,其实通过判断当前屏幕的宽高来决定是不是横屏或者竖屏:
竖屏时:宽<高
横屏时:宽>高
以上在IOS8、9中测试通过
参考链接
http://simayang.com/archives/405.html