nom*_*oda 4 parameter-passing notificationcenter swift
我是Swift的初学者,正在尝试通过NotificationCenter初始化功能。“ ViewController.swift”中的观察者调用function 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)
}
Run Code Online (Sandbox Code Playgroud)
...的参数为class Ítem:
class Item: NSObject {
let name: String
let iconName: String
init(name: String, iconName: String) {
self.name = name
self.iconName = iconName
}
}
Run Code Online (Sandbox Code Playgroud)
该通知从“ 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])
}
Run Code Online (Sandbox Code Playgroud)
如何将items[indexPath.row]“ menu.swift”中的对象值分配给reload“ ViewController.swift”中的函数参数?
如果要在注册到的类周围传递对象NotificationCenter,则应将其放入.userInfo传递给观察者函数的通知对象字典中:
NotificationCenter.default.addObserver(self, selector: #selector(reload), name: Notification(name: "reload"), object: nil)
Run Code Online (Sandbox Code Playgroud)
-
let userInfo = ["item": items[indexPath.row]]
NotificationCenter.default.post(name: "reload", object: nil, userInfo: userInfo)
Run Code Online (Sandbox Code Playgroud)
-
func reload(_ notification: Notification) {
if let target = notification.userInfo?["item"] as? Item {
print(target.name)
print(target.iconName)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2254 次 |
| 最近记录: |