【问题标题】:Getting the name of UIVIewController in App delegate swift在 App 委托中快速获取 UIVIewController 的名称
【发布时间】:2018-11-07 11:49:29
【问题描述】:

目前我实现了 Reachability is AppDelegate.swift 文件。这是我确定何时连接或断开互联网的代码

@objc func reachabilityChanged(note: Notification) {
    let reachability = note.object as! Reachability
    if (reachability.connection != .none) {
    }
    else
    {
        currentView()
    }

}

这段代码可以很好地检测互联网是连接还是断开。 现在,如果 Internet 断开连接,我想知道我当前在我的 navigationController 中的哪个 viewController,并且我想修改那个 viewController 的 UI 以通知用户 Internet 已断开连接。我正在尝试使用以下代码在我的 navigationStack 中获取当前 viewController,但它不起作用

if let window = UIApplication.shared.delegate?.window {
    if var viewController = window?.rootViewController {
        // handle navigation controllers
        if(viewController is UINavigationController){
            viewController = (viewController as! UINavigationController).visibleViewController!
        }
        print (viewController)
    }
}

【问题讨论】:

  • 为什么需要这个名字?你要完成什么?顺便说一句 - type(of:).
  • 我需要知道哪个视图控制器处于活动状态,这样我才能执行特定于每个视图控制器的某些功能
  • 好的,但是获得它的名字并不是正确的方法。使用isif let as?
  • 你的意思是我应该使用 viewController is (className) 并检查?
  • 这是一种解决方案。最好的解决方案取决于一旦您知道它是什么类型的视图控制器但您没有在问题中解释这一点,您真正需要做什么。

标签: ios swift uiviewcontroller uinavigationcontroller appdelegate


【解决方案1】:

如果他们的视图在屏幕上,我建议您使用 NotificationCenter 并向观察者发送通知以执行您想要的操作。在发送通知时让您的 VC 成为观察者并实施选择器。

如果您不知道如何检查视图是否在屏幕上,请查看此答案: How to tell if UIViewController's view is visible

【讨论】:

    猜你喜欢
    • 2014-12-09
    • 1970-01-01
    • 2023-03-12
    • 2015-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-09
    相关资源
    最近更新 更多