iOS开发iOS DeveloperiOS开发

一种iOS屏幕旋转管理策略

2016-04-05  本文已影响311人  呼神护卫

公司的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")
上一篇下一篇

猜你喜欢

热点阅读