使用#selector传递参数 [英] Passing parameters with #selector

查看:721
本文介绍了使用#selector传递参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Swift的初学者,我正在尝试通过NotificationCenter初始化功能. "ViewController.swift"中的观察者调用函数reload:

I'm a beginner to Swift and I'm trying to initiate a function through NotificationCenter. The observer in 'ViewController.swift' calls on 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)
}

...,其参数为类Ítem:

... which has a parameter of class Ítem:

class Item: NSObject {
    let name: String
    let iconName: String
    init(name: String, iconName: String) {
        self.name = name
        self.iconName = iconName
    }
}

该通知是从"menu.swift"发布的:

The notification is posted from "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的参数?

How do I assign the value of object items[indexPath.row] from 'menu.swift' to the parameter of function reload in 'ViewController.swift'?

推荐答案

如果要将对象传递给已注册到NotificationCenter的类,则应将其放入

If you want to pass an object around classes that are registered to NotificationCenter, you should put that into .userInfo dictionary of notification object that is passed to observer function:

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)
  }
}

这篇关于使用#selector传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆