Presenting view controllers on detached view controllers

Yury Alexandrov picture Yury Alexandrov · Aug 20, 2014 · Viewed 14.5k times · Source

I have sideViewController with a button and Action, which present new view controller by clicking this button.

class sideViewController: UIViewController {
    @IBOutlet var buttonVC1 : UIButton!
    @IBAction func goToVC1 () {
        var VC1 = self.storyboard.instantiateViewControllerWithIdentifier("ViewController") as ViewController
        presentViewController(VC1, animated:true, completion: nil)
    }
}

I use this in main view controller:

class ViewController: UIViewController {
    var menu : sideViewController!
    override func viewDidLoad() {
        super.viewDidLoad()
        menu = self.storyboard.instantiateViewControllerWithIdentifier("menu") as      sideViewController
        menu.view.frame = CGRect(x: 0, y: 0, width: 160, height: 480)
        view.addSubview(menu.view)
}

when I click this button, the problem is: "Presenting view controllers on detached view controllers is discouraged"

What should I do to fix this?

Answer

bolnad picture bolnad · Jan 7, 2015

I just ran into this same warning myself, and realized that I'm getting it because when I was calling

self.presentViewController

I was calling it on a view controller that wasn't attached to the UIWindow through the view hierarchy. You need to change what your doing to delay calling presentViewController until you know the view is on the view stack. This would be done in ViewDidLoad or ViewDidAppear, or if your coming from a background state, waiting until your app is in the active state