How to lock orientation of one view controller to portrait mode only in Swift

后端 未结 16 2196
梦谈多话
梦谈多话 2020-11-22 12:07

Since my app got support for all orientation. I would like to lock only portrait mode to specific UIViewController.

e.g. assume it was Tabbed Application and when Si

16条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 12:32

    To set Landscape orientation to all view of your app & allow only one view to All orientations (to be able to add camera roll for example):

    In AppDelegate.swift:

    var adaptOrientation = false
    

    In: didFinishLaunchingWithOptions

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "adaptOrientationAction:", name:"adaptOrientationAction", object: nil)
    

    Elsewhere in AppDelegate.swift:

    func application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> Int {
        return checkOrientation(self.window?.rootViewController)
    }
    
    func checkOrientation(viewController:UIViewController?)-> Int{
        if (adaptOrientation == false){
            return Int(UIInterfaceOrientationMask.Landscape.rawValue)
        }else {
            return Int(UIInterfaceOrientationMask.All.rawValue)
        }
    }
    
    func adaptOrientationAction(notification: NSNotification){
        if adaptOrientation == false {
            adaptOrientation = true
        }else {
            adaptOrientation = false
        }
    }
    

    Then in the view that segue to the one you want to be able to have All orientations:

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
        if (segue.identifier == "YOURSEGUE") {
            NSNotificationCenter.defaultCenter().postNotificationName("adaptOrientationAction", object: nil)
        }
    }
    
    override func viewWillAppear(animated: Bool) {
        if adaptOrientation == true {
            NSNotificationCenter.defaultCenter().postNotificationName("adaptOrientationAction", object: nil)
        }
    }
    

    Last thing is to tick Device orientation: - Portrait - Landscape Left - Landscape Right

提交回复
热议问题