Swift - Accessing AppDelegate window from viewController

theDC picture theDC · May 4, 2015 · Viewed 42.7k times · Source

I make walkthrough (onboarding flow) in my app and I'd like to have a skip button. The button is located on viewController, so I figured out that the best way to move to another viewController would be access app delegate window.

However, it keeps getting me an error that AppDelegate.Type does not have a member called "window".

@IBAction func skipWalkthrough(sender: AnyObject) {
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    AppDelegate.window!.rootViewController = RootViewController   
}

Is there anything wrong with such approach?

Thanks in advance!

Answer

Stefan Salatic picture Stefan Salatic · May 4, 2015

You have a typo it is supposed to be appDelegate not AppDelegate. So like this:

@IBAction func skipWalkthrough(sender: AnyObject) {
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    appDelegate.window!.rootViewController = RootViewController   
}

Swift 3.2

@IBAction func skipWalkthrough(_ sender: AnyObject) {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        appDelegate.window!.rootViewController = controller
    }