一种iOS屏幕旋转管理策略

公司的App屏幕旋转的需求是这样的:大部分界面是只支持Portrait的,只有少数界面支持自动横屏。

所有的UIViewController都重载一下supportedInterfaceOrientations等一系列方法显然太繁琐。好在StackOverflow上有人提供了一个相对简单的方法

1、在app delegate类中添加一个属性restrictRotation
2、重载方法

func application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> UIInterfaceOrientationMask

根据restrictRotation的值来返回相应的UIInterfaceOrientationMask:

var restrictRotation:Bool = true
    
func application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> UIInterfaceOrientationMask {
    if restrictRotation {
        return UIInterfaceOrientationMask.Portrait
    }else{
        return UIInterfaceOrientationMask.All
    }
}

这样,在需要支持自动横屏的UIViewController中适时设置一下restrictRotation = false就可以了。

比如在应用播放视频的时候需要支持自动横屏,可以继承MPMoviePlayerViewController

class MoviePlayerVC: MPMoviePlayerViewController {
    
    var oldRestrictRotation:Bool?
    
    override func viewWillAppear(animated: Bool) {
        if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
            oldRestrictRotation = appDelegate.restrictRotation
            appDelegate.restrictRotation = false
        }
    }
    
    override func viewWillDisappear(animated: Bool) {
        if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
            appDelegate.restrictRotation = oldRestrictRotation ?? true
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

这样,视频播放页面出现时就会支持自动横屏,关闭播放页面后,自动横屏也关闭了。

有一个小问题:如果在MoviePlayerVC处于横屏状态时结束播放,回到上一个View Controller后,有时上一个View Controller会变成横屏的状态。此时设备方向是横的,页面不会自动转回来。

再次感谢万能的StackOverflow,这种情况也有相应的解决办法

viewDidAppear中执行下面的代码,将设备方向强制设为Portrait,就会让View Controller自动旋转过来了:

let value = UIInterfaceOrientation.LandscapeLeft.rawValue
UIDevice.currentDevice().setValue(value, forKey: "orientation")
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 14,223评论 4 61
  • 成功需要多少年 有个少年想成为少林寺最出色的弟子。他问大师:“我要多少年才能那么出色?” 大师回答说:“至少十年。...
    小策谈车阅读 4,430评论 0 0
  • 早上微博圈,被一个弯弯的姑娘刷屏了。不仅是微博,各种媒体公众号不停地转发微博。实在是太可怕了,作为女生在这...
    青柠summer阅读 3,570评论 0 0
  • 背景 英文以空格作为分隔符,而中文词语之间没有分隔; 在中文里,“词”和“词组”边界模糊现代汉语的基本表达单元虽然...
    翼徳阅读 7,666评论 0 5
  • 今年我25岁,在25岁之前,我没有认真想过爱情和婚姻的定义,依照所见所闻,我大概认为爱情里异性相吸,与物质无关,讲...
    求求女先生阅读 3,602评论 0 2