加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift – 使用#selector传递参数

发布时间:2020-12-14 04:38:18 所属栏目:百科 来源:网络整理
导读:我是 Swift的初学者,我正试图通过NotificationCenter启动一个功能. ‘ViewController.swift’中的观察者调用函数重载: override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self,selector: #selector(reload),name:
我是 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)
  }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读