overAiding shouldAutorotate不在Swift 3中工作

pab*_*ros 29 autorotate ios swift

我试图阻止轮换UIViewController,我无法做到这一点.

我正在做这样的事情:

open override var shouldAutorotate: Bool {
    get {
        return false
    }
}

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    get {
        return .portrait
    }
}
Run Code Online (Sandbox Code Playgroud)

UIViewControler剧照旋转.UIViewController位于以模态方式打开的UINavigationController中.

我从这里看了很多问题,没有一个答案适合我.

在Swift 2中,我曾经覆盖shouldAutorotate但在Swift 3中,该功能不再存在.

我怎么能在Swift 3中做到这一点,我曾经在Swift 2中做过什么?

pab*_*ros 43

如果我可以多次重现这种行为,我不知道为什么要投票来结束这个问题.它UIViewController是一个UINavigationController打开的模态.

这就是我为解决问题所做的.

我创建了这个类,并设置UINavigationControllerUIViewController我要阻止旋转的那个包含

class NavigationController: UINavigationController { 

    override var shouldAutorotate: Bool {
        return false
    }

    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }

}
Run Code Online (Sandbox Code Playgroud)

就是这样,它对我有用


Sup*_*vin 10

将此代码添加到AppDelegate.swift

var orientationLock = UIInterfaceOrientationMask.all
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
    return self.orientationLock
}

struct AppUtility {
    static func lockOrientation(_ orientation: UIInterfaceOrientationMask) {
        if let delegate = UIApplication.shared.delegate as? AppDelegate {
            delegate.orientationLock = orientation
        }
    }

    static func lockOrientation(_ orientation: UIInterfaceOrientationMask, andRotateTo rotateOrientation:UIInterfaceOrientation) {
        self.lockOrientation(orientation)
        UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation")
    }
}
Run Code Online (Sandbox Code Playgroud)

添加到要强制方向的viewcontroller:

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    //let value = UIInterfaceOrientation.landscapeLeft.rawValue
    //UIDevice.current.setValue(value, forKey: "orientation")


    AppDelegate.AppUtility.lockOrientation(.landscapeLeft)

}
Run Code Online (Sandbox Code Playgroud)