我需要在 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/