gpt4 book ai didi

ios - Swift - 当应用程序进入后台状态时,从 AppDelegate 更新 RootViewController 中的值

转载 作者:IT王子 更新时间:2023-10-29 05:47:13 26 4
gpt4 key购买 nike

我有一个只有一个主视图的简单 View 应用程序。

当应用程序进入后台状态时,我试图在 View 内的标签中显示更新的时间值。

场景是:

1 - 单 View 应用程序项目

2 - 只有一个 View (ViewController) 和一个 Label 来显示日期

3 - 在 AppDelegate:applicationWillEnterForeground 中获取当前时间

func applicationWillEnterForegound(application: UIAPplication){
var date:String = GetDate()
--> update View Label with date here
}

4 - 在 ViewController 上显示当前时间

我正在尝试使用委托(delegate),但问题是 View 是应用程序中最后一个可见元素,并且调用了一次 viewDidLoad、viewWillAppear 等方法。

最佳答案

正如其他人所指出的,您可以使用 Notification 框架从您的 View Controller 中执行此操作,因此您的 appDelegate 不需要引用您的 View Controller 。在您的 Controller 中添加这样一行:

NSNotificationCenter.defaultCenter().addObserver(self,
selector: #selector(appWillEnterForeground),
name: NSNotification.Name.UIApplicationWillEnterForeground,
object: nil

在 Swift 3 中,语法略有变化:

NotificationCenter.default.addObserver(self, 
selector: #selector(appWillEnterForeground),
name: NSNotification.Name.UIApplicationWillEnterForeground,
object: nil)

在 Swift 4.2 中,语法再次发生变化:

NotificationCenter.default.addObserver(self, 
selector: #selector(appWillEnterForeground),
name: UIApplication.willEnterForegroundNotification,
object: nil)

然后在选择器中定义你命名的函数:

@objc func appWillEnterForeground() {
//...
}

关于ios - Swift - 当应用程序进入后台状态时,从 AppDelegate 更新 RootViewController 中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38590671/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com