繁体   English   中英

iOS Swift 5 手动更改设备方向

[英]iOS Swift 5 Change device orientation manually

在 iOS swift 5 项目中,我只需要在一个场景中支持多个设备方向。

我有以下要求:

  • 如果设备旋转,则不应更改设备方向。
  • 如果点击按钮,则应更改设备方向(向左旋转)

这意味着只有一个UIViewController用户应该能够通过点击按钮手动更改设备方向,但旋转设备不应该做任何事情。

实现此目的的一种简单方法是在AppDelegate (_:supportedInterfaceOrientationsFor:)上设置您支持的方向

在那里创建一个局部变量

var orientation: UIInterfaceOrientationMask = .portrait

然后将该变量作为支持的方向返回

    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        return orientation
    }

在要通过触摸按钮旋转的ViewController上,您可以更改应用程序委托上支持的方向,而不是强制更改设备方向以便旋转视图

    private func changeSupportedOrientation() {
        let delegate = UIApplication.shared.delegate as! AppDelegate
        switch delegate.orientation {
        case .portrait:
            delegate.orientation = .landscapeLeft
        default:
            delegate.orientation = .portrait
        }
    }

    @IBAction func rotateButtonTapped(_ sender: UIButton) {
        changeSupportedOrientation()
        switch UIDevice.current.orientation {
        case .landscapeLeft:
            UIDevice.current.setValue(UIDeviceOrientation.portrait.rawValue, forKey: "orientation")
        default:
            UIDevice.current.setValue(UIDeviceOrientation.landscapeLeft.rawValue, forKey: "orientation")
        }
    }

这将强制设备的方向改变,然后旋转您的视图。 如果您再次点击按钮,方向将回到.portrait

请小心使用它,因为您需要真正考虑您的导航堆栈,以确保只有导航堆栈的顶部支持旋转,并且只有在将方向设置回原始.portrait后才能从导航堆栈中弹出只要。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM