Swift - Accessing AppDelegate window from viewController
47,517
Solution 1
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
}
Solution 2
This is for with or without Storyboard and it is working for Swift 3+
let appDelegate = UIApplication.shared.delegate as? AppDelegate
let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
let homeController = mainStoryboard.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController
appDelegate?.window?.rootViewController = homeController
Solution 3
Swift 3
This is a better way:
if let window = NSApplication.shared().windows.first {
window.acceptsMouseMovedEvents = true;
}
Solution 4
appDelegate.window!.rootViewController
is not working in Swift 5
Here is working code
Add below extension
extension UIWindow {
static var key: UIWindow! {
if #available(iOS 13, *) {
return UIApplication.shared.windows.first { $0.isKeyWindow }
} else {
return UIApplication.shared.keyWindow
}
}
}
use
let mainSB = UIStoryboard(name: "Main", bundle: nil)
if let RootVc = mainSB.instantiateViewController(withIdentifier: "NavigationController") as? UINavigationController{
UIWindow.key.rootViewController = RootVc
}
UIWindow.key // to access only window
Solution 5
You can also use conditional binding to reach the window
.
if let window = UIApplication.shared.windows.first {
// use window here.
}
Comments
-
theDC almost 3 years
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!