我是 Swift的初学者,我正试图通过NotificationCenter启动一个功能. ‘ViewController.swift’中的观察者调用函数重载: override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, s
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(reload), name: NSNotification.Name(rawValue: "reload"), object: nil)
}
func reload(target: Item) {
print(target.name)
print(target.iconName)
}
…具有类Ítem的参数:
class Item: NSObject {
let name: String
let iconName: String
init(name: String, iconName: String) {
self.name = name
self.iconName = iconName
}
}
通知从“menu.swift”发布:
class menu: UIView, UITableViewDelegate, UITableViewDataSource {
let items: [Item] = {
return [Item(name: "Johnny", iconName: "A"), Item(name: "Alexis", iconName: "B"), Item(name: "Steven", iconName: "C")]
}()
...
func tableView(_ tableView: UITableView, didSelectRowAt indexPath:
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "reload"), object: items[indexPath.row])
}
如何将’menu.swift’中的对象项[indexPath.row]的值分配给’ViewController.swift’中函数reload的参数?
如果要在注册到NotificationCenter的类周围传递对象,则应将其放入传递给observer函数的通知对象的.userInfo字典中:
NotificationCenter.default.addObserver(self, selector: #selector(reload), name: Notification(name: "reload"), object: nil)
–
let userInfo = ["item": items[indexPath.row]] NotificationCenter.default.post(name: "reload", object: nil, userInfo: userInfo)
–
func reload(_ notification: Notification) {
if let target = notification.userInfo?["item"] as? Item {
print(target.name)
print(target.iconName)
}
}
