首页 文章

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

提问于
浏览
8

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

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

场景是:

1 - 单视图应用程序项目

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

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

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

4 - 在ViewController上显示当前时间

我正在尝试代理,但问题是视图是应用程序和方法中的最后一个可见元素,因为viewDidLoad,viewWillAppear被调用一次 .

3 回答

  • 1

    正如其他人所说,您可以使用通知框架在视图控制器中执行此操作,这样您的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)
    

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

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

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

  • 1

    谢谢你的回答 . 我现在在主视图中实现了一个Notification并解决了问题 .

    override func viewDidLoad(){
        super.viewDidLoad()
    
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.updateDate), name: UIApplicationWillEnterForegroundNotification, object: nil)
    }
    
    func updateDate(){
        labelInfo.text = theDate
    }
    

    谢谢

相关问题