【问题标题】:Swift - Update a value in RootViewController from AppDelegate when the app comes to background stateSwift - 当应用程序进入后台状态时,从 AppDelegate 更新 RootViewController 中的值
【发布时间】:2016-07-26 13:02:30
【问题描述】:

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

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

场景是:

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 等方法被调用一次。

【问题讨论】:

  • 这种情况下最好使用NSNotification

标签: ios iphone swift uiviewcontroller


【解决方案1】:

正如其他人所指出的,您可以使用 Notification 框架在您的视图控制器中执行此操作,这样您的 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() {
   //...
}

【讨论】:

  • 非常感谢,这很有帮助
  • 对 swift3 的额外小改动:名称:Notification.Name.UIApplicationWillEnterForeground,
  • 既然你是在观察某些东西进入后台之后,什么时候会移除观察者? viewDidDisapear 进入后台时不会删除观察者吗?
【解决方案2】:

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

【讨论】:

  • 谢谢,根据您的回答,我搜索了有关听众的信息,发现了有趣的讨论。
【解决方案3】:

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

override func viewDidLoad(){
    super.viewDidLoad()

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

func updateDate(){
    labelInfo.text = theDate
}

谢谢

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-12
    • 1970-01-01
    • 1970-01-01
    • 2011-05-18
    • 1970-01-01
    • 2013-02-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多