如何仅在 Swift 中将一个视图控制器的方向锁定为纵向模式

2023-12-20

因为我的应用程序支持所有方向。我想仅将纵向模式锁定到特定的 UIViewController。

例如假设它是选项卡式应用程序,并且当登录视图以模态方式出现时,我只希望登录视图仅处于纵向模式,无论用户如何旋转设备或当前设备方向如何


当你有一个复杂的视图层次结构时,事情可能会变得非常混乱,比如有多个导航控制器和/或选项卡视图控制器。

此实现将其放在各个视图控制器上以设置它们何时想要锁定方向,而不是依赖应用程序委托通过迭代子视图来找到它们。

斯威夫特 3、4、5

在应用程序委托中:

/// 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")
        UINavigationController.attemptRotationToDeviceOrientation()
    }

}

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

 override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(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)
}

如果是 iPad 或通用应用程序

Make sure that "Requires full screen" is checked in Target Settings -> General -> Deployment Info. supportedInterfaceOrientationsFor delegate will not get called if that is not checked. enter image description here

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何仅在 Swift 中将一个视图控制器的方向锁定为纵向模式 的相关文章

随机推荐