gpt4 book ai didi

swift - 如何仅在 Swift 中将一个 View Controller 的方向锁定为纵向模式

转载 作者:行者123 更新时间:2023-11-30 12:44:28 26 4
gpt4 key购买 nike

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

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

最佳答案

当你有一个复杂的 View 层次结构时,事情可能会变得非常困惑,比如有多个导航 Controller 和/或选项卡 View Controller 。

此实现将其放在各个 View Controller 上,以便在它们想要锁定方向时进行设置,而不是依赖应用程序委托(delegate)通过迭代 subview 来找到它们。

swift 3、4、5

在 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")
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 或通用应用程序

确保在目标设置 -> 常规 -> 部署信息中选中“需要全屏”。如果未选中,则不会调用 supportedInterfaceOrientationsFor 委托(delegate)。 enter image description here

关于swift - 如何仅在 Swift 中将一个 View Controller 的方向锁定为纵向模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41807237/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com