ios - 使用 Objective C AppDelegate 在单个 Swift VC 中锁定方向

标签 ios objective-c iphone swift

我有一个 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/

相关文章:

iphone - Apple 会接受带有已弃用代码的应用程序吗?

iphone - 单击时如何使自定义按钮键像iPhone按钮键一样大

ios - swift 3 : URL Image makes UITableView scroll slow issue

iphone - 谷歌 OAuth 错误 -1001

ios - tableView.tableHeaderView = UISearchDisplayController.searchBar;并调用 setContentInset : ; searchBar is not drawn when i scroll the table

ios - 将iOS应用崩溃报告从库发送到服务器

iphone - 调用委托(delegate)的委托(delegate)

ios - 如何从另一个 UIPopover Controller 打开 UIPopover Controller ?

ios - 防止方法 Swizzling Objective-c

ios - 在 iOS 中使用 Twilio 发送短信