首页 > 解决方案 > NotificationCenter 处理程序更新变量但 UILabel 保持不变

问题描述

使用 Xcode 10.1 在 mini iPad OS 12.1.1 上运行应用程序

我正在向 NotificationCenter 发布通知,并且处理函数更新 UILabelsetupProgress以显示数据导入的进度。

这曾经工作正常,但最近停止工作,很可能是由于我做了什么,但我想不出是什么。

PM代码中是一个打印到控制台的函数 - 它告诉我,self.setupProgress.text事实上,设置正确并在数据加载时按预期更改,但是相应的 UILabel 不会更新。

初始的 UILabel 文本是这样设置的

if !self.update_type.isEmpty && self.update_type == "setup_import" {
    self.setupProgress.text = "I've told the server that this is a clean install"
}

并且工作正常 - 但是随着导入的进行,在处理程序函数(如下)中我没有得到任何更新,直到 import_progress == "And now the end is upon us ..." 此时 UILabel 正确更新并且一切都按预期进行。

func handleImportNotification(_ notification:Notification) {

    self.setupProgress.text = import_progress

    // should show something like 
    // `Importing F4RES : 0 of : 1395` 
    // `Importing F4RES : 500 of : 1395`
    // etc...

    PM(#line, function: #function, str1: self.setupProgress.text)
    // prints the correct updates to the console

    if import_progress == "And now the end is upon us ..." {
        self.makeShopOptions()
        self.loadingImage.stopAnimating()
        self.performSegue(withIdentifier: "setup_to_splash", sender: self)
    }
}

该应用程序继续正常工作 - 只是没有预期的 UILabel 更新。

提前感谢您的任何想法。

标签: swiftxcode10.1

解决方案


您正在向通知中心发布通知。你介意展示如何以及何时?

假设您正在使用NotificationCenter.default.post notificationName:方法,则处理程序应采用 type 的参数Notification。否则它不会响应通知更新。

处理程序函数应如下所示: func handleImportNotification(notification: Notification) { ... }

和观察者:

var observer: NSObjectProtocol?

func someFunction() {
    observer = NotificationCenter.default.addObserver(forName: object: queue: using: { (Notification) in
        //Update UILabel or call the associated function
    }))
}

尝试这个。


推荐阅读