我有一个 Objetive-C 应用程序委托(delegate),它是我正在与自己的项目交互的项目的一部分。我正在尝试锁定方向,但看起来旧方法(如下)不再有效。在 viewDidLoad
中设置方向会旋转屏幕,但允许用户旋转回 portrait
。我尝试转换为 "override var"
但没有成功。当前的解决方案(下面的链接)看起来都涉及 app delegate
调用,但我找不到 Swift 调用 Objective C
app delegate 的解决方案。
How to lock orientation of one view controller to portrait mode only in Swift
override func shouldAutorotate() -> Bool {
return false
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.landscapeRight
}
最佳答案
强制只有一个 Controller 处于横向。 经理:
class OrientationManager {
static let shared = OrientationManager()
/// you can set any orientation to lock
var orientationLock = UIInterfaceOrientationMask.portrait
/// lock orientation and force to rotate device
func lock(for orientation: UIInterfaceOrientationMask, rotateTo rotateOrientation: UIInterfaceOrientation) {
orientationLock = orientation
UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation")
}
}
用法:
1) 添加代码到AppDelegate
func application(_ application: UIApplication,
supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
return OrientationManager.shared.orientationLock
}
2) 在 Controller 中使用
open class LandscapeController: UIViewController {
/// orientation for one controller
override open func viewDidLoad() {
super.viewDidLoad()
OrientationManager.shared.lock(for: .landscape, rotateTo: .landscapeLeft)
}
/// set previous state of orientation or any new one
override open func viewWillDisappear(_ animated : Bool) {
super.viewWillDisappear(animated)
OrientationManager.shared.lock(for: .portrait, rotateTo: .portrait)
}
}
关于ios - 使用 Objective C AppDelegate 在单个 Swift VC 中锁定方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43687011/