只有在Swift中,如何将一个视图控制器的方向锁定到纵向模式

前端之家收集整理的这篇文章主要介绍了只有在Swift中,如何将一个视图控制器的方向锁定到纵向模式前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
由于我的应用程序支持所有方向.我想只将肖像模式锁定到特定的UIViewController.

(e.g. Assume it was Tabbed Application and when SignIn View appear modally,I only want that SignIn View to the portrait mode only no
matter how the user rotate the device or how the current device
orientation will be)

当您具有复杂的视图层次结构时,如拥有多个导航控制器和/或制表视图控制器,事情会变得相当混乱.

该实现将它放在个人视图控制器上,以便设置何时锁定方向,而不是依赖App代理通过遍历子视图来查找它们.

Swift 3

在AppDelegate中:

/// set orientations you want to be allowed in this property by default
var orientationLock = UIInterfaceOrientationMask.all

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

在其他一些全局结构或帮助类中,我创建了AppUtility:

struct AppUtility {

    static func lockOrientation(_ orientation: UIInterfaceOrientationMask) {

        if let delegate = UIApplication.shared.delegate as? AppDelegate {
            delegate.orientationLock = orientation
        }
    }

    /// OPTIONAL Added method to adjust lock and rotate to the desired orientation
    static func lockOrientation(_ orientation: UIInterfaceOrientationMask,andRotateTo rotateOrientation:UIInterfaceOrientation) {

        self.lockOrientation(orientation)

        UIDevice.current.setValue(rotateOrientation.rawValue,forKey: "orientation")
    }

}

然后在所需的ViewController中锁定方向:

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    AppUtility.lockOrientation(.portrait)
    // Or to rotate and lock
    // AppUtility.lockOrientation(.portrait,andRotateTo: .portrait)

}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    // Don't forget to reset when view is being removed
    AppUtility.lockOrientation(.all)
}
原文链接:https://www.f2er.com/swift/319711.html

猜你在找的Swift相关文章