Swift - 当应用程序进入后台状态

时间:2016-07-26 13:02:30

标签: ios iphone swift uiviewcontroller

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

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

场景是:

1 - 单一视图应用程序项目

2 - 只有一个View(ViewController),其中一个Label显示日期

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

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

4 - 在ViewController上显示当前时间

我尝试使用委托,但问题是该视图是应用程序和方法中的最后一个可见元素,因为viewDidLoad,viewWillAppear被调用一次。

3 个答案:

答案 0 :(得分:16)

正如其他人所说,您可以使用通知框架在视图控制器中执行此操作,这样您的appDelegate就不需要引用您的视图控制器。在控制器中添加如下所示的行:

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() {
   //...
}

答案 1 :(得分:1)

您可以在UIApplicationWillEnterForegroundNotification内收听ViewController。如果您知道其视图可见,则可以找到日期并更改自己的标签。

答案 2 :(得分:1)

谢谢大家的回答。我现在在主视图中实现了一个Notification并解决了这个问题。

override func viewDidLoad(){
    super.viewDidLoad()

    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.updateDate), name: UIApplicationWillEnterForegroundNotification, object: nil)
}

func updateDate(){
    labelInfo.text = theDate
}

由于