如何从appdelegate中的viewcontroller调用函数? (Swift)
所以基本上我试图在AppDelegate.swift中运行Refresh(位于ViewController.swift)函数。在搜索了5个小时的更好的部分后,我无法弄清楚为什么这不起作用。 这里是我的功能:如何从appdelegate中的viewcontroller调用函数? (Swift)
func Refresh(){
if(Count==0 && QuickActionChecker==true){
Previous.text=String(TipArray[CountCurrent])
Current.text=String(TipArray[CountCurrent])
Deliveries.text="\(Runs)"
}
if(Count>0 && QuickActionChecker==true){
Previous.text=String(TipArray[CountCurrent-1])
Current.text=String(Total)
Deliveries.text="\(Runs)"
}
}
在我Appdelegate.swift我已经将其设置为主要初始化的ViewController:
let Main = ViewController()
和这里就是我试图从运行功能(力触按主屏幕快速行动):
func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
if shortcutItem.type == "com.Sicarix.Ticket.Add5"{
if(CountCurrent==0){
TipArray.append(5)
Count=Count+1
CountCurrent=CountCurrent+2
Total=TipArray.reduce(0) {$0+$1}
Runs=Runs+1
QuickActionChecker=true
Main.Refresh()
}
else{
TipArray.append(5)
Count=Count+1
CountCurrent=CountCurrent+1
Total=TipArray.reduce(0) {$0+$1}
Runs=Runs+1
QuickActionChecker=true
Main.Refresh()
}
}
}
然而,当我尝试使用它的快捷方式打开应用到白色屏幕和在那里停留。控制台吐出:
fatal error: unexpectedly found nil while unwrapping an Optional value
代码运行正常,当我删除Main.Refresh(),它只是没有在我的应用程序更新标签,因此对于功能的需求。 请帮助,我准备好继续前进这个错误.... 也请记住,我甚至还没有在一个星期内快速编码,所以请分解什么是最好的错能够。 TIA
更改您的viewController对象
let nextVC = storyboard?.instantiateViewController(withIdentifier:"ViewController") as! ViewController
的问题是,你正在使用ViewController()
实例化一个新的ViewController
和ViewController
不添加到您的视图控制器层次。
您需要使用您的Storyboard
实例化ViewController
使用let mainVC = UIStoryboard(name: "Main", bundle: "nil").instantiateViewController(withIdentifier:"ViewController") as! ViewController
并确保您的标识符设置在Storyboard
。
如果您不使用Storyboard
,另一种解决方案是将要在UI中显示的文本存储在数据源变量中,并只更新'AppDelegate'中的这些变量,然后将这些变量的内容加载到标签中'viewDidLoad'或'viewWillAppear'。
你是如何定义数组的? – farzadshbfn
在Swift中,变量和方法名应该以小写字母开头。 – Moritz