Swift - 从 viewController 访问 AppDelegate window

Swift - Accessing AppDelegate window from viewController

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

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

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

这样的做法有什么问题吗?

提前致谢!

你打错了,应该是 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
    }

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

应该是:

appDelegate.window!.rootViewController = RootViewController   

这适用于有或没有情节提要,它适用于 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

Swift 3

这是更好的方法:

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

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

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

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

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

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

if let window = UIApplication.shared.windows.first {
    // use window here.
}

appDelegate.window!.rootViewControllerSwift 5

中不起作用

这是工作代码

添加以下扩展名

extension UIWindow {
    static var key: UIWindow! {
        if #available(iOS 13, *) {
            return UIApplication.shared.windows.first { [=10=].isKeyWindow }
        } else {
            return UIApplication.shared.keyWindow
        }
    }
}

使用

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