How to get the values of multiple textFields in UITableView with dynamic cells?

前端 未结 2 551
攒了一身酷
攒了一身酷 2021-01-26 00:28

In a UIViewController I have a UITableView with 1 Dynamic Prototype cell of class type TextInputTableViewCell.
In the Content View of the prototype cell I am a

2条回答
  •  误落风尘
    2021-01-26 01:15

    The usual problem to be solved is: The user has a edited a text field in a table view cell, and now we want to update the data model accordingly. But which cell contains this text field?

    The notion "which" really means: what is the index path represented by the containing cell? If we knew that, we could easily update the model, because if our table view data source is correctly designed, we already know how to access the model by means of the index path.

    So what I do is simply walk up the view hierarchy from the text field to the cell, and then ask the table view what index path this cell represents. This is a commonly used pattern in my apps:

    func textFieldDidEndEditing(_ textField: UITextField) {
        var v : UIView = textField
        repeat { v = v.superview! } while !(v is UITableViewCell)
        let cell = v as! MyCell // or UITableViewCell or whatever
        let ip = self.tableView.indexPath(for:cell)!
        // and now we have the index path! update the model
    }
    

提交回复
热议问题