加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 05:35:55 所属栏目:百科 来源:网络整理
导读:由于我的应用程序支持所有方向.我想只将肖像模式锁定到特定的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
由于我的应用程序支持所有方向.我想只将肖像模式锁定到特定的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)
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读