This question already has answers here:
How do I get a reference to the app delegate in Swift?
(18个答案)
去年关门了。
我正在使用Swift和最新的Xcode版本。
我在AppDelegate.swift中有这个代码:
func testPrint(string: String) {
    print(string)
}

我可以成功地从文件ViewController.swift调用函数,如下所示:
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.testPrint(string: "Hello!")

但是,如果我试图从TodayViewController.swift调用函数,这是针对ApplesToday Extension,则会出现以下错误:
使用未声明的类型“AppDelegate”
为什么?

最佳答案

试试下面这些:

let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.testPrint(string: "Hello!")

编辑:
“今日扩展”和应用程序生活在不同的环境中,因此这是不可能的。

关于ios - Xcode;如何从另一个ViewController调用AppDelegate中的函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51772152/

10-11 22:01
查看更多