我是
Swift的初学者,我正试图通过NotificationCenter启动一个功能. ‘ViewController.swift’中的观察者调用函数重载:
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,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) } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。