首页 > 解决方案 > 如何从 TextField 委托函数之一打印包含 UITextField 的 TableView 单元格的 indexPath?

问题描述

这是我生成自定义单元格的地方,其中存储了一个名为“indexPath”的属性。此外,每个单元格都包含一个 UITextField。文本字段委托功能如下。这两个函数都存在于同一个 ViewController 中。

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

    let cell = tableView.dequeueReusableCell(withIdentifier: "ReusableCell", for: indexPath) as! BuyerCell

    cell.nameField.delegate = self
    cell.indexPath = indexPath
    cell.nameField.text = potentialBuyers[indexPath.row]
    return cell
}


这是 TextField 委托函数。我需要从委托函数中打印单元格的 indexPath 。

func textFieldDidEndEditing(_ textField: UITextField) {
    print("called textFieldDidEndEditing")

    //I need to print the cell's indexPath here 

}

标签: iosswiftuitableviewdelegatesuitextfield

解决方案


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

let cell = tableView.dequeueReusableCell(withIdentifier: "ReusableCell", for: indexPath) as! BuyerCell

cell.nameField.delegate = self
cell.indexPath = indexPath
cell.nameField.text = potentialBuyers[indexPath.row]
// add tag for the textField
cell.nameField.tag = indexPath.row
return cell

}

现在在 textFieldDelegate 方法中像这样获取您的单元格和 cell.indexPath

func textFieldDidEndEditing(_ textField: UITextField) {
    print("called textFieldDidEndEditing")

    let cell = tableView.cellForRow(at: IndexPath(row: textField.tag, section: 0)) as! BuyerCell
    print(cell.indexPath)

}

推荐阅读