swift – 使用#selector传递参数

swift – 使用#selector传递参数,第1张

概述我是 Swift的初学者,我正试图通过NotificationCenter启动一个功能. ‘ViewController.swift’中的观察者调用函数重载: override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #select 我是 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)  }}
总结

以上是内存溢出为你收集整理的swift – 使用#selector传递参数全部内容,希望文章能够帮你解决swift – 使用#selector传递参数所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1005720.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-22
下一篇 2022-05-22

发表评论

登录后才能评论

评论列表(0条)

保存