简体   繁体   中英

iOS Swift 5 Change device orientation manually

In iOS swift 5 project I need to support multiple device orientations in only one scene.

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.

One simple way to accomplish this is by setting your supported orientation on the 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

    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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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