How to rotate orientation programmatically in Swift?

后端 未结 5 1284
有刺的猬
有刺的猬 2020-12-11 15:53

I tried the next:

UIDevice.currentDevice().setValue(UIInterfaceOrientation.Portrait.rawValue, forKey: \"orientation\")

on

         


        
5条回答
  •  北荒
    北荒 (楼主)
    2020-12-11 16:13

    Swift 4:

    Step1:

    In Appdelegate - Declare deviceOrientation var which is portrait by default

    import UIKit
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate {
        var window: UIWindow?
        var deviceOrientation = UIInterfaceOrientationMask.portrait
        func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
            return deviceOrientation
        }
    }
    

    Step 2:

    In your certain ViewController write this to change orientation -

     override func viewWillAppear(_ animated: Bool) {
         appDelegate.deviceOrientation = .landscapeLeft
         let value = UIInterfaceOrientation.landscapeLeft.rawValue
         UIDevice.current.setValue(value, forKey: "orientation")
     } 
    

提交回复
热议问题