Swift UILabel在应用程序进入后台时为零(错误)



我有一些代码可以更改UILabel的文本,当应用程序第一次运行时它工作正常,但是当我关闭它(应用程序进入后台)然后我重新打开它时,UILabel nil并且无法再次设置文本。

文本设置为 UILabel viewDidLoad()函数,我在函数中调用viewDidLoad() applicationWillEnterForeground再次将文本设置为UILabel - 那是它崩溃时,错误fatal error: unexpectedly found nil while unwrapping an Optional value。我调试了它,找到nilUILabel

以下是AppDelegate.swift中的一些代码:

func applicationWillEnterForeground(application: UIApplication) { 
     ViewController().refresh() 
}

ViewController.swift

func refresh() {
    self.viewDidLoad()
}

您是否知道为什么当应用程序进入后台时UILabel变得nil

与其尝试从应用委托保存对视图控制器的引用,不如简单地让视图控制器订阅前台入口事件 -

viewDidLoad中添加以下内容

NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("enteringForeground:"),
  name: UIApplicationWillEnterForegroundNotification, object: nil)

向视图控制器添加函数

func enteringForeground(notification: NSNotification) {
   // Whatever you need to do to refresh UI
   // DO NOT CALL viewDidLoad
}
deinit {
   NSNotificationCenter.defaultCenter().removeObserver(self)
}

最新更新