首页 > 解决方案 > 从 appdelegate 更改 UILabel 文本

问题描述

我有一个 UIViewcontroller,比如说“DialerViewController”,它有一个 UILabel @IBOutlet weak var statusText: UILabel!,它的默认值为“pending”,如何使用应用程序委托更改 statusText 的值,假设应用程序委托从服务器下载文本并需要在完成后更新 statusText。

我是快速开发的新手,解决这个问题的最佳方法是什么?

标签: iosswiftuilabelappdelegate

解决方案


如果它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


推荐阅读