Comment faire pivoter l'orientation par programmation dans Swift?

J'ai essayé le suivant:

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

sur

viewWillAppear

mais il ne fonctionne pas. Comment puis-je tourner mon écran sur viewWillAppear?

Mise à JOUR

J'utilise le code suivant pour le verrouillage de l'orientation:

var shouldRotate = true
func application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> Int {
    if shouldRotate == true {
        return Int(UIInterfaceOrientationMask.Portrait.rawValue)
    } else {
        return Int(UIInterfaceOrientationMask.LandscapeLeft.rawValue)
    }
}

Swift 4.0

  private func application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> Int {
        if shouldRotate == true {
            return Int(UIInterfaceOrientationMask.portrait.rawValue)
        } else {
            return Int(UIInterfaceOrientationMask.landscapeLeft.rawValue)
        }
    }

et dans mon PREMIER contrôleur de viewWillAppear j'ai mis:

if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
    appDelegate.shouldRotate = true
}

dans mon DEUXIÈME contrôleur:

if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
    appDelegate.shouldRotate = false
}

donc, quand j'ai le dos à partir de la DEUXIÈME contrôleur à la PREMIÈRE:

Je le faire pivoter à gauche de ne pas tourner, tourner à droite - rien, tourner à gauche, encore une fois - qu'il tourne.

Comment puis-je résoudre ce problème?

OriginalL'auteur Orkhan Alizade | 2015-09-02