使用#selector传递参数

时间:2017-03-27 20:39:29

标签: swift parameter-passing notificationcenter

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

...其参数类为Í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的参数?

1 个答案:

答案 0 :(得分:6)

如果要围绕注册到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)
  }
}