通过委托发送数据

Send Data Via Delegate

我有一个 TableView,我想使用 prepare(for segue) 方法将数据传输到另一个 ViewController,但我想使用委托方法进行学习。我这样做了:

protocol SendName {
    func send(name: String)
}

class ContactsTVC: UITableViewController, GetData {

    var delegate: SendName?
    var contacts = ["Anja Deo","Hans Peter","Müller Schmitz"] {
        didSet {
            tableView.reloadData()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = "Kontakte"
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return contacts.count
    }


    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        ...
    }


    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "showContactDetailView" {
            let destination = segue.destination as! ContactDetailViewVC
            if let delegate = delegate  {
                let selectedContact = contacts[(tableView.indexPathForSelectedRow!.row)]
                 delegate.send(name: selectedContact)
            }
        }
    } 
}

当然所有这些都在 UITableViewController class.

在 ViewController 我想去 我这样做了:

class ContactDetailViewVC: UIViewController, SendName {

    var selectedContact: ContactsTVC?
    override func viewDidLoad() {
        super.viewDidLoad()

    selectedContact?.delegate = self

    }

    func send(name: String) {
        self.title = name
        print("Should work")
    }
}

这不是像在 prepare 方法中那样使用委托的地方,一旦你得到 let destination = segue.destination as! ContactDetailViewVC 你就知道它是 ContactDetailViewVC 类型并且编译器知道ContactDetailViewVC 符合 SendName 协议,因此您可以使用 destination.send(name: selectedContact)

destination 上调用发送方法

您的方法将因此更改为:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destination = segue.destination as? ContactDetailViewVC {
        let selectedContact = contacts[(tableView.indexPathForSelectedRow!.row)]
        destination.send(name: selectedContact)
    }
}

您可以直接使用delegate对象来调用发送函数。

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "showContactDetailView" {
        let destination = segue.destination as! ContactDetailViewVC
        delegate.send(name: contacts[(tableView.indexPathForSelectedRow!.row)])
    }
} 

您必须在 ContactsTVC 本身中设置 var delegate: SendName? 的值。代表应该是弱的,以避免保留循环,weak var delegate: SendName?