您的位置:首页 > 移动开发 > IOS开发

iOS 横竖屏控制

2016-04-11 10:56 525 查看
在公司的App项目中,要求有些界面不知横屏模式,有些界面要支持横屏模式。

第一,我们要确保App本身是支持横竖屏的。IOS屏幕旋转控制与旋转事件处理 设定App本身允许转屏

再次,我的App里面都是走UINavigationController进行界面push切换的,所以首先创建一个UINavigationController的子类,并设定允许转屏:(代码如下)@implementation AppExtendNavigationController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark 重新书写转屏方法
-(UIInterfaceOrientationMask)supportedInterfaceOrientations
{
return [self.viewControllers.lastObject supportedInterfaceOrientations];
}
-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
return [self.viewControllers.lastObject preferredInterfaceOrientationForPresentation];
}
-(BOOL)shouldAutorotate{
return self.visibleViewController.shouldAutorotate;
}

在你App项目中不想支持横屏的界面(不支持转屏切换),添加如下代码:

#pragma mark 转屏方法 不允许横屏,只支持竖屏显示
-(UIInterfaceOrientationMask)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskPortrait ;
}
- (BOOL)shouldAutorotate
{
return NO;
}
-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
return UIInterfaceOrientationPortrait;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation{
return NO;
}

在你App项目中想支持横屏显示(转屏切换),添加如下代码:

- (BOOL)shouldAutorotate {
return YES;
}
-(UIInterfaceOrientationMask)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskAll;
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
return UIInterfaceOrientationPortrait;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}

如果你想捕获旋转屏幕的事件,你可以添加如下代码,在这几个方法里面做相应的处理,代码如下:
</pre><pre name="code" class="objc">- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
{
[super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
[coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> 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<UIViewControllerTransitionCoordinatorContext> context) {
NSLog(@"动画播放完之后逻辑处理");
}];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  苹果 xcode ios app 文档