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

标签 ios iphone swift uiviewcontroller

我有一个只有一个主视图的简单 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/

相关文章:

ios - 对 double 进行算术运算

ios - 从 tableView 中删除行时更改默认背景颜色

iphone - iFrame 仅在移动版 Safari 中显示灰线

ios - 从自定义 TableViewCell 中重新加载 TableView

objective-c - 尝试将 Swift 与 Obj C header 用于 Coda2 插件。获取错误 : Undefined symbols for architecture x86_64

没有 Storyboard的 iOS 应用程序(大小类别和设备类型限制)

ios - 循环加载自定义单元格 Swift

iphone - 在 CALayer 的 mask 区域周围添加阴影

ios - 无法创建 PDF 和打印超过 60 页(内存升高和崩溃)

swift - 如何创建一个受限于结构的泛型类?