ios - 如何在应用程序委托(delegate)中调用 View Controller 中的方法?

标签 ios swift

我需要在 AppDelegate 的 ViewController 类中调用一个方法。这是该方法的样子:

class ViewController: UIViewController {

    func myFunction() {
        ...
    }
}

我试过使用 window.rootViewController,但它告诉我方法 myFunction 不存在,因为 rootViewController 是 UIViewController 类型。

我也试过

var vc = ViewController()
self.vc.myFunction()

但这是在创建 ViewController 类的新实例,这也不是我想要的。

这是我需要从中调用 myFunction 的 AppDelegate 代码部分:

class AppDelegate: UIResponder, UIApplicationDelegate {

    func handleEvent() {
        if UIApplication.shared.applicationState == .active {
            // call myFunction()
        }
        else {
            ...
        }
    }
}

上下文: 我正在学习地理围栏教程:https://www.raywenderlich.com/136165/core-location-geofencing-tutorial

由于即使在应用程序关闭时也会监视用户位置,因此当触发事件时,应使用 AppDelegate 来处理事件,因为尚未加载 View Controller 。

在我处理事件的 AppDelegate 中,如果应用程序处于事件状态,我想弹出一个警报让用户选择停止监视位置。停止位置监控的函数 (myFunction) 在 View Controller 中。

最佳答案

如果它的根很简单:

(window.rootViewController as? ViewController)?.myFunction()

如果它在导航 Controller 之上

((window.rootViewController as? UINavigationController)?.topViewController as? ViewController)?.myFunction()

但无论哪种情况,这都很奇怪,而且可能不是正确的做法。请改用 NotificationCenter 并在您的 AppDelegate 中发布通知名称,然后让 ViewController 监听消息并做出相应响应。

关于ios - 如何在应用程序委托(delegate)中调用 View Controller 中的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43565912/

相关文章:

ios - uitableview 中的 Uilabel 在调试模拟器颜色混合层中不显示不透明而不透明

ios - @IBInspectable NSLayoutConstraint 不工作 Xcode 8.2.1 (8C1002)

ios - 是否可以为 Collection View 添加拖动以水平重新加载?

ios - 动画圆形 UIBezierPath 而不舍入笔划

ios - 如何使用 MVVM 设计模式绑定(bind)对象?

Facebook 的 iOS URL 方案

swift UITextView

iphone - 点击时自动选择文本字段中的文本

cocoa-touch - 防止 MFMailComposeViewController 缩放动画 GIF

iphone - IOS - 如何在滚动元素时更新元素的界面?