iOS-Developer-SwiftiOS学习Swift

Swift 4.2 禁止旋转屏幕-强制屏幕旋转

2018-11-22  本文已影响912人  JasonFive

禁止旋转屏幕,有两种方法

1、直接Xcode写死,简单方便 (不推荐)
1542854748635.jpg

但是这样有个问题,当需要旋转屏幕或者,在倒入某些第三方的时候,如果不支持屏幕旋转,在使用第三方的时候应用会蹦。所以,这样写-不推荐


2、用代码控制屏幕旋转与否
override var shouldAutorotate: Bool
override var supportedInterfaceOrientations: UIInterfaceOrientationMask

这两个方法就可以控制屏幕的旋转和不旋转了

a、在Appdelegate中设置三个属性
var isForceLandscape:Bool = false
var isForcePortrait:Bool = false
var isForceAllDerictions:Bool = false //支持所有方向

然后重写 func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?)

/// 设置屏幕支持的方向
    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        if isForceAllDerictions == true {
            return .all
        } else if isForceLandscape == true {
            return .landscape
        } else if isForcePortrait == true {
            return .portrait
        }
        return .portrait
    }

到这儿,就已经可以禁止屏幕旋转了

b、强制旋转横屏

在需要强制旋转屏幕的VC中添加以下代码就可以实现屏幕强制横屏

    /// 屏幕旋转
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        //self.setNavigationBarHidden(hidden: true)
        forceOrientationLandscape()
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        //self.setNavigationBarHidden(hidden: false)
        forceOrientationPortrait()
    }
    override var shouldAutorotate: Bool {
        get {
            return true
        }
    }
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        get {
            return .landscapeRight
        }
    }
    // 强制旋转横屏
    func forceOrientationLandscape() {
        let appdelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate
        appdelegate.isForceLandscape = true
        appdelegate.isForcePortrait = false
        _ = appdelegate.application(UIApplication.shared, supportedInterfaceOrientationsFor: view.window)
        let oriention = UIInterfaceOrientation.landscapeRight // 设置屏幕为横屏
        UIDevice.current.setValue(oriention.rawValue, forKey: "orientation")
        UIViewController.attemptRotationToDeviceOrientation()
    }
    // 强制旋转竖屏
    func forceOrientationPortrait() {
        let appdelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate
        appdelegate.isForceLandscape = false
        appdelegate.isForcePortrait = true
        _ = appdelegate.application(UIApplication.shared, supportedInterfaceOrientationsFor: view.window)
        let oriention = UIInterfaceOrientation.portrait // 设置屏幕为竖屏
        UIDevice.current.setValue(oriention.rawValue, forKey: "orientation")
        UIViewController.attemptRotationToDeviceOrientation()
    }

这样当进入当前VC的时候就可以实现横屏,退出当前VC为竖屏
由于时间关系,目前就先写这么多,后续再更新

上一篇 下一篇

猜你喜欢

热点阅读