Swift - 从viewController访问AppDelegate窗口

问题描述 投票:20回答:5

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

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

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

这种方法有什么问题吗?

提前致谢!

ios swift uiviewcontroller appdelegate
5个回答
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
    }

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

8
投票

斯威夫特3

这是一种更好的方法:

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

1
投票

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

应该:

appDelegate.window!.rootViewController = RootViewController   

0
投票

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

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

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

0
投票

您还可以使用条件绑定来到达window

if let window = UIApplication.shared.windows.first {
    // use window here.
}
© www.soinside.com 2019 - 2024. All rights reserved.