Swift - Accessing AppDelegate window from viewController
我在应用程序中进行了演练(入门流程),我想有一个跳过按钮。
该按钮位于viewController上,因此我发现移动到另一个viewController的最佳方法是访问应用程序委托窗口。
但是,它总是使我得到一个错误,即AppDelegate.Type没有名为" window"的成员。
1 2 3 4 | @IBAction func skipWalkthrough(sender: AnyObject) { let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate AppDelegate.window!.rootViewController = RootViewController } |
这种方法有什么问题吗?
提前致谢!
您有错字,应该是
1 2 3 4 | @IBAction func skipWalkthrough(sender: AnyObject) { let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate appDelegate.window!.rootViewController = RootViewController } |
斯威夫特3.2
1 2 3 4 | @IBAction func skipWalkthrough(_ sender: AnyObject) { let appDelegate = UIApplication.shared.delegate as! AppDelegate appDelegate.window!.rootViewController = controller } |
适用于有无Storyboard,适用于Swift 3+
1 2 3 4 | 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 |
迅捷3
这是一个更好的方法:
1 2 3 | if let window = NSApplication.shared().windows.first { window.acceptsMouseMovedEvents = true; } |
您也可以使用条件绑定来达到
1 2 3 | if let window = UIApplication.shared.windows.first { // use window here. } |
您正在使用协议名称(即
应该:
1 | appDelegate.window!.rootViewController = RootViewController |
这是工作代码
1 2 3 4 5 6 7 8 9 | if let window = UIApplication.shared.windows.first{ let mainSB = UIStoryboard(name:"Main", bundle: nil) if let RootVc = mainSB.instantiateViewController(withIdentifier:"NavigationController") as? UINavigationController{ window.rootViewController = RootVc window.makeKeyAndVisible() } } |
您可以从应用程序中的任何位置访问标签栏。 在下面使用:
1 2 3 4 5 6 7 8 | let appDelegate = UIApplication.shared.delegate as! AppDelegate if let tabBarController = appDelegate.window!.rootViewController as? UITabBarController { if let tabItems = tabBarController.tabBar.items { let tabItem = tabItems[2] tabItem.badgeValue ="5" //enter any value } } |
该解决方案适用于:
登录/注册后,以编程方式添加
1 2 3 | let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate appDelegate.window!.rootViewController = tabs appDelegate.window!.makeKeyAndVisible() |