使用#selector 传递参数

Passing parameters with #selector

我是 Swift 的初学者,我正在尝试通过 NotificationCenter 启动一个功能。 'ViewController.swift' 中的观察者调用函数 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)
}

... 其参数为 class Í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' 中对象 items[indexPath.row] 的值赋给 'ViewController.swift' 中函数 reload 的参数?

如果你想在 类 周围传递一个注册到 NotificationCenter 的对象,你应该把它放入传递给观察者函数的通知对象的 .userInfo 字典中:

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