ios - 从 appdelegate 更改 UILabel 文本
问题描述
我有一个 UIViewcontroller,比如说“DialerViewController”,它有一个 UILabel @IBOutlet weak var statusText: UILabel!,它的默认值为“pending”,如何使用应用程序委托更改 statusText 的值,假设应用程序委托从服务器下载文本并需要在完成后更新 statusText。
我是快速开发的新手,解决这个问题的最佳方法是什么?
解决方案
如果它DialerViewController
是您的应用程序中唯一的视图控制器,您可以这样处理它......
(window?.rootViewController as? DialerViewController)?.statusText?.text = "YOURTEXT"
另一种选择是让DialerViewController
实例观察一些特定的通知,并在从服务器下载文本时将此通知发布到应用程序委托中。
// create an extension for your own notification
extension Notification.Name {
static let textWasDownloadedNotification = Notification.Name("textWasDownloadedNotification")
}
class DialerViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// make your dialer view controller listen to your new notification
NotificationCenter.default.addObserver(self, selector: #selector(updateLabel), name: .textWasDownloadedNotification, object: nil)
}
// function that gets called when a notification is received
@objc func updateLabel(_ notification: Notification) {
// get the new text from the notification's `userInfo` dictionary
let text = notification.userInfo?["text"] as? String
// update the label
statusText.text = text
}
}
// somewhere in your app delegate...
// prepare the `userInfo` dictionary with the information that is needed
let userInfo = ["text": "This is the new text."]
// post the notification
NotificationCenter.default.post(name: .textWasDownloadedNotification,
object: nil,
userInfo: userInfo)
请参阅https://developer.apple.com/documentation/foundation/notificationcenter。
推荐阅读
- css - CSS 不使用 !important 并遵循 DRY 原则
- html - 角度错误“无法读取未定义的属性‘firstName’”
- python - Lxml 获取所有项目,但也要测试下一个项目 - Python
- reactjs - 使用浏览器后退按钮关闭多个嵌套的 Material UI 对话框 - reactjs
- ruby - Ruby 方法可以访问隐式块参数吗?
- python - Python pyspark 将 DF 写入 .csv 并存储在本地 C 盘
- mongodb - Docker 容器中的 MongoDB 错误:尝试在主机“127.0.0.1:27017”上运行命令“isMaster”时出现网络错误
- python - 如何获得过滤数据框的平均值
- python - 更改图形大小
- c++ - 我在在线法官上遇到此错误〜