美文网首页iOS开发iOS 遇到的问题学无止境
iOS将单个控制器设为横屏、页面横屏

iOS将单个控制器设为横屏、页面横屏

作者: BYQiu | 来源:发表于2016-08-09 17:14 被阅读314次
最近项目中拍照页面需要设置为横屏,需求如下

进入拍摄页面后将页面强制设为横屏,拍照结束后回复竖屏。
简述为:A->B(横屏)


屏幕快照 2016-07-29 下午5.50.02.png
1. 首先在AppDelegate中添加一个公开属性restrictRotation并添加一个方法、该方法是是否允许屏幕转向
/** 允许转向 */
-(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    if(self.restrictRotation == YES)
        return UIInterfaceOrientationMaskLandscapeRight;
//        return UIInterfaceOrientationMaskLandscape;
    else
        
        return UIInterfaceOrientationMaskPortrait;
}
2. 在需要设置横屏的页面中添加下列方法
/**
 *  设置屏幕旋转
 *
 *  @param restriction yes or no
 */
- (void)restrictRotation:(BOOL) restriction {
    AppDelegate* appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    appDelegate.restrictRotation = restriction;
    
}

在进入页面时允许屏幕旋转,并设置旋转的方向,代码如下

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
 
    [self restrictRotation:YES];
    NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight];
    [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
    
}
// 离开时禁止旋转并将屏幕方向设为竖屏
-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    [self restrictRotation:NO];
    NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
    [[UIDevice currentDevice] setValue:value forKey:@"orientation"];

}

实现了将单个控制器设为横屏的功能。
但是,新的问题出现了:当B控制器返回A时,A控制器页变也为横屏(需要将手机转向才能恢复)
解决办法很简单:
在A控制器的-(void)viewWillAppear:(BOOL)animated方法中添加,再次设为竖屏即可

NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
    [[UIDevice currentDevice] setValue:value forKey:@"orientation"];

相关文章

网友评论

  • 路人张某某:大佬.拍照启用横屏 然后加上相框 能够提供一份简单的demo或者是思路吗? 最近混合开发碰见这个需求
    路人张某某:@BYQiu 好的 我试试 3Q
    BYQiu:@路人张某某 Google搜索iOS图片合成,把照相机获取的图像和相框的背景图合成。
  • 92aaf53fd4df:照片的方向有处理嘛?
    BYQiu:这里只是提供横屏的一种方案,图片处理又是另外一回事了
  • 9o後侽孓:大神太牛了,赞一个
    BYQiu:@9o後侽孓 不客气,大神不敢当哈...:smile:
  • 捞月亮的猴子:横向布局怎么搞?代码里面。
    BYQiu:@捞月亮的猴子 那就不用按比例了,布局时注意屏幕的宽和高的值对调了,其他的都一样
    捞月亮的猴子:@Developer_iOS 我这里的需求是,全部是竖屏,一个页面是横屏,是个信息页面,不是相机。
    BYQiu:@捞月亮的猴子 和正向布局一样,我建议你按比例进行布局,后面截图方便一点

本文标题:iOS将单个控制器设为横屏、页面横屏

本文链接:https://www.haomeiwen.com/subject/ssmzjttx.html