我是Swift的初学者,我试图通过NotificationCenter启动功能。 ViewController.swift中的观察者'调用函数reload
:
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'中分配对象items[indexPath.row]
的值?在' ViewController.swift'中的函数reload
的参数?
答案 0 :(得分:6)
如果要围绕注册到NotificationCenter
的类传递对象,则应将其放入传递给观察者函数的.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)
}
}