繁体   English   中英

Swift - 从 viewController 访问 AppDelegate 窗口

[英]Swift - Accessing AppDelegate window from viewController

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

但是,它不断给我一个错误,即 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   
}

斯威夫特 3.2

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

这适用于有或没有 Storyboard,它适用于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

斯威夫特 3

这是一个更好的方法:

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

您还可以使用条件绑定来访问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 { $0.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

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

应该:

appDelegate.window!.rootViewController = RootViewController   

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM