简体   繁体   English

iOS Swift 5 手动更改设备方向

[英]iOS Swift 5 Change device orientation manually

In iOS swift 5 project I need to support multiple device orientations in only one scene.在 iOS swift 5 项目中,我只需要在一个场景中支持多个设备方向。

I have the following requirements:我有以下要求:

  • If device is rotated, device orientation should not be changed.如果设备旋转,则不应更改设备方向。
  • If button is tapped, device orientation should be changed (left rotation)如果点击按钮,则应更改设备方向(向左旋转)

This means that in only one UIViewController user should be able to change device orientation manually by tapping on a button, but rotating the device should not do anything.这意味着只有一个UIViewController用户应该能够通过点击按钮手动更改设备方向,但旋转设备不应该做任何事情。

One simple way to accomplish this is by setting your supported orientation on the AppDelegate (_:supportedInterfaceOrientationsFor:)实现此目的的一种简单方法是在AppDelegate (_:supportedInterfaceOrientationsFor:)上设置您支持的方向

Create a local variable there在那里创建一个局部变量

var orientation: UIInterfaceOrientationMask = .portrait

and then return that variable as supported orientation然后将该变量作为支持的方向返回

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

on the ViewController that you want to rotate with a touch of a button, you can change the supported orientation on the app delegate and than force the device orientation to change so that the view is rotated在要通过触摸按钮旋转的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")
        }
    }

this will force the orientation of the device to change and then rotate your view.这将强制设备的方向改变,然后旋转您的视图。 If you tap on the button again the orientation will be back to .portrait如果您再次点击按钮,方向将回到.portrait

Please be careful of using this as you need to really consider your navigation stack to make sure that only the top of the navigation stack support rotation and can only be pop from the navigation stack after the orientation is set back to the original which is .portrait only.请小心使用它,因为您需要真正考虑您的导航堆栈,以确保只有导航堆栈的顶部支持旋转,并且只有在将方向设置回原始.portrait后才能从导航堆栈中弹出只要。

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

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