不同的UIViewController类利用NotificationCenter进行数据通信

以下是一个利用NotificationCenter进行数据通信的示例,它展示了如何在两个不同的UIViewController类之间通过NotificationCenter进行数据传递。
我们在第一个UIViewController类中定义了一个计数器,并在点击button按钮时进行加1操作,同时发送一个名为counterChangedNotification的通知。第二个UIViewController类中注册该通知,当接收到通知时,获取counter变量的值,并将其更新到UI界面上。具体代码如下:
FirstViewController类:
import UIKit
import NotificationCenter

@main
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    let counterChangedNotification = Notification.Name("CounterChangedNotification")

    // ...
}

class FirstViewController: UIViewController {

    @IBOutlet weak var label: UILabel!

    var counter = 0

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func buttonPressed(_ sender: UIButton) {
        counter += 1
let appDelegate = UIApplication.shared.delegate as! AppDelegate
        NotificationCenter.default.post(name: appDelegate.counterChangedNotification, object: counter)
        label.text = "\\\\(counter)"
    }
}
SecondViewController类:
import UIKit
import NotificationCenter

class SecondViewController: UIViewController {

    @IBOutlet weak var label: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
let appDelegate = UIApplication.shared.delegate as! AppDelegate
        NotificationCenter.default.addObserver(self, selector: #selector(updateLabel(_:)), name: appDelegate.counterChangedNotification, object: nil)
    }

    deinit {
        NotificationCenter.default.removeObserver(self)
    }

    @objc func updateLabel(_ notification: Notification) {
        guard let counter = notification.object as? Int else { return }
        label.text = "\\\\(counter)"
    }
}
通过以上代码,我们在两个UIViewController类之间,通过NotificationCenter完成了数据传递。
你觉得这篇文章怎么样?
YYDS
比心
加油
菜狗
views

Loading Comments...