Swift - 从viewController访问AppDelegate窗口

时间:2015-05-04 10:23:53

标签: ios swift uiviewcontroller appdelegate

我在我的应用程序中进行了演练(入门流程),我想要一个跳过按钮。 该按钮位于viewController上,因此我发现移动到另一个viewController的最佳方法是访问app delegate窗口。

但是,它一直给我一个错误,即AppDelegate.Type没有名为“window”的成员。

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

这种做法有什么问题吗?

提前致谢!

8 个答案:

答案 0 :(得分:44)

您输错了appDelegate而不是AppDelegate。像这样:

@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
    }

答案 1 :(得分:17)

这适用于有或没有故事板,它适用于swift3 +

    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

答案 2 :(得分:8)

Swift 3

这是一种更好的方式:

    if let window = NSApplication.shared().windows.first {
        window.acceptsMouseMovedEvents = true;
    }

答案 3 :(得分:1)

您正在使用协议名称(即AppDelegate)而不是实例:

应该是:

appDelegate.window!.rootViewController = RootViewController   

答案 4 :(得分:1)

您还可以使用条件绑定来到达There was a problem with your request. Error code 13

window

答案 5 :(得分:1)

appDelegate.window!.rootViewController Swift 5

中不起作用

这里是工作代码

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()
    }
}

答案 6 :(得分:0)

此解决方案适用于:  登录/注册后以编程方式添加UITabbarController

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    appDelegate.window!.rootViewController = tabs //()
    appDelegate.window!.makeKeyAndVisible()

答案 7 :(得分:0)

您可以在应用程序的任何位置访问标签栏。在下面使用:

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
    }
}