Forcer le mode paysage dans un ViewController à L'aide de Swift
j'essaie de forcer une seule vue dans mon application en mode paysage, Je vais appeler
override func shouldAutorotate() -> Bool {
    print("shouldAutorotate")
    return false
}
override func supportedInterfaceOrientations() -> Int {
    print("supportedInterfaceOrientations")
    return Int(UIInterfaceOrientationMask.LandscapeLeft.rawValue)
}
override func preferredInterfaceOrientationForPresentation() -> UIInterfaceOrientation {
    return UIInterfaceOrientation.LandscapeLeft
}
la vue est lancée en mode portrait, et continue à tourner quand je change l'orientation de l'appareil. 
Le shouldAutorotate n'est jamais appelé.
Toute aide serait appréciée.
11 réponses
Il peut être utile pour les autres, j'ai trouvé un moyen de forcer l'affichage de lancer en mode paysage:
Mettre cela dans le viewDidLoad():
let value = UIInterfaceOrientation.LandscapeLeft.rawValue
UIDevice.currentDevice().setValue(value, forKey: "orientation")
et
override func shouldAutorotate() -> Bool {
    return true
}
Swift 4
override func viewDidLoad() {
    super.viewDidLoad()
    let value = UIInterfaceOrientation.landscapeLeft.rawValue
    UIDevice.current.setValue(value, forKey: "orientation")
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    return .landscapeLeft
}
override var shouldAutorotate: Bool {
    return true
}
Swift 3
override func viewDidLoad() {
    super.viewDidLoad()
    let value = UIInterfaceOrientation.landscapeLeft.rawValue
    UIDevice.current.setValue(value, forKey: "orientation")
}
private func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
    return UIInterfaceOrientationMask.landscapeLeft
}
private func shouldAutorotate() -> Bool {
    return true
}
Utiliser Swift 2.2
Essaie:
let value = UIInterfaceOrientation.LandscapeLeft.rawValue
UIDevice.currentDevice().setValue(value, forKey: "orientation")
Suivi De:
UIViewController.attemptRotationToDeviceOrientation()
From Apple UIViewController Class Reference:
certains contrôleurs de vue peuvent vouloir utiliser des conditions spécifiques à l'application pour déterminer quelles orientations d'interface sont supportées. Si votre contrôleur de vue fait cela, lorsque ces conditions changent, votre application devrait appeler cette méthode de classe. Le système tente immédiatement de tourner dans la nouvelle orientation.
Puis, comme d'autres l'ont suggéré, remplacer les méthodes suivantes:
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
    return UIInterfaceOrientationMask.LandscapeLeft
}
override func shouldAutorotate() -> Bool {
    return true
}
j'avais un problème similaire avec une vue de signature et cela l'a résolu pour moi.
Swift 4 Testé dans le iOS 11
Vous pouvez spécifier l'orientation dans objectifduprojet -> général -> Déploymentinfo (orientation de L'appareil) - > Portrait (Landscapeleft et Landscaperight en option)
AppDelegate
var orientationLock = UIInterfaceOrientationMask.portrait
    var myOrientation: UIInterfaceOrientationMask = .portrait
    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        return myOrientation
    }
LandScpaeViewController
override func viewDidLoad() {
        super.viewDidLoad()
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        appDelegate.myOrientation = .landscape
}
OnDismissButtonTap
let appDelegate = UIApplication.shared.delegate as! AppDelegate
 appDelegate.myOrientation = .portrait
c'est tout. :)
j'avais besoin de forcer un contrôleur à s'orienter vers le portrait. Ajouter cela a fonctionné pour moi.
swift 4 avec iOS 11
override var   supportedInterfaceOrientations : UIInterfaceOrientationMask{
    return  .portrait
}
pour moi, les meilleurs résultats ont été obtenus en combinant la réponse de Zeesha et la réponse de sazz.
ajouter les lignes suivantes À AppDelegate.swift:
var orientationLock = UIInterfaceOrientationMask.portrait
var myOrientation: UIInterfaceOrientationMask = .portrait
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
    return myOrientation
}  
ajouter la ligne suivante à votre classe de controller view:
let appDel = UIApplication.shared.delegate as! AppDelegate
 ajouter les lignes suivantes à votre contrôleur de vue viewDidLoad():
appDel.myOrientation = .landscape
UIDevice.current.setValue(UIInterfaceOrientation.landscapeLeft.rawValue, forKey: "orientation")
(optionnel) Ajoutez cette ligne à votre fonction de rejet:
appDel.myOrientation = .portrait
UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
ce que font ces lignes de code est de définir l'orientation par défaut à portrait, tournez le paysage quand le contrôleur de vue se charge, puis réinitialisez-le enfin à portrait une fois que le contrôleur de vue se ferme.
fonctionne avec Swift 2.2
 func application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> UIInterfaceOrientationMask {
    if self.window?.rootViewController?.presentedViewController is SignatureViewController {
        let secondController = self.window!.rootViewController!.presentedViewController as! SignatureViewController
        if secondController.isPresented {
            return UIInterfaceOrientationMask.LandscapeLeft;
        } else {
            return UIInterfaceOrientationMask.Portrait;
        }
    } else {
        return UIInterfaceOrientationMask.Portrait;
    }
}
Swift 3. Cela verrouille l'orientation chaque fois que l'utilisateur ouvre de nouveau l'application.
class MyViewController: UIViewController {
    ...
    override func viewDidLoad() {
        super.viewDidLoad()
        // Receive notification when app is brought to foreground
        NotificationCenter.default.addObserver(self, selector: #selector(self.onDidBecomeActive), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
    }
    // Handle notification
    func onDidBecomeActive() {
        setOrientationLandscape()
    }
    // Change orientation to landscape
    private func setOrientationLandscape() {
        if !UIDevice.current.orientation.isLandscape {
            let value = UIInterfaceOrientation.landscapeLeft.rawValue
            UIDevice.current.setValue(value, forKey:"orientation")
            UIViewController.attemptRotationToDeviceOrientation()
        }
    }
    // Only allow landscape left
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return UIInterfaceOrientationMask.landscapeLeft
    }
    /*
    // Allow rotation - this seems unnecessary
    private func shouldAutoRotate() -> Bool {
        return true
    }
    */
    ...
}
Swift 4
en Essayant de garder l'orientation, rien n'a fonctionné, mais c'est pour moi:
...        
override func viewDidLoad() {
       super.viewDidLoad()
       forcelandscapeRight()
       let notificationCenter = NotificationCenter.default
       notificationCenter.addObserver(self, selector: #selector(forcelandscapeRight), name: Notification.Name.UIDeviceOrientationDidChange, object: nil)
    }
    @objc func forcelandscapeRight() {
        let value = UIInterfaceOrientation.landscapeRight.rawValue
        UIDevice.current.setValue(value, forKey: "orientation")
    }
....
Selon  documentation des interfacesorientations supportéesshouldAutorotate la méthode doit retourner true ou YES dans L'Objectif-C pour que le supportedInterfaceOrientations sont pris en compte.
class CustomUIViewController : UIViewController{
    override var   supportedInterfaceOrientations : UIInterfaceOrientationMask{
        return  .landscapeLeft
    }
}
class ViewController: CustomUIViewController {
.
.
.
}