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

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

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

当您具有复杂的视图层次结构时,事情会变得很混乱,例如具有多个导航控制器和/或选项卡视图控制器。

此实现将其置于各个视图控制器上,以便在它们希望锁定方向时进行设置,而不是依赖于App Delegate通过遍历子视图来找到它们。

斯威夫特3&4

在AppDelegate中:

/// set orientations you want to be allowed in this property by defaultvar orientationLock = UIInterfaceOrientationMask.allfunc application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {        return self.orientationLock}

在其他一些全局struct或helper类中,我在这里创建了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或Universal App

确保在“目标设置”->“常规”->“部署信息”中选中了“需要全屏显示”。

supportedInterfaceOrientationsFor
如果未选中,则不会调用委托。



欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5622437.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-15
下一篇2022-12-15

发表评论

登录后才能评论

评论列表(0条)

    保存