只有在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)
}

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...