1

我正在尝试访问indexPath函数内部的数组以更新该数组的数据,但我不知道如何将其indexPath作为参数(尤其是调用时传递的内容)传递给函数,或者这是否是解决方案。

我包含cellForRowAt说明这个函数是如何访问indexPath的。

var cryptosArray: [Cryptos] = []

extension WalletTableViewController: UITableViewDelegate, UITableViewDataSource, CryptoCellDelegate {

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

        let crypto = cryptosArray[indexPath.row]

        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! WalletTableViewCell
        cell.setCrypto(crypto: crypto)
        cell.delegate = self
        cell.amountTextField.delegate = self

        return cell
    }

    func cellAmountEntered(_ walletTableViewCell: WalletTableViewCell) {

         if walletTableViewCell.amountTextField.text == "" {
            return
        }
        let str = walletTableViewCell.amountTextField.text

        let crypto = cryptosArray[indexPath.row] //<---- How to do that?

        crypto.amount = walletTableViewCell.amountTextField.text

        //Then update array's amount value at correct index


        walletTableViewCell.amountTextField.text = ""

    }


}
4

2 回答 2

5

而不是破解某些东西,只需要求tableView告诉你indexPath给定单元格的内容:

// use indexPath(for:) on tableView
let indexPath = tableView.indexPath(for: walletTableViewCell)

// then you can simply use it
let crypto = cryptosArray[indexPath.row]

UITableView.indexPath(for:) 文档说:

返回表示给定表格视图单元格的行和部分的索引路径。

这正是你想要的,你不想破解indexPath牢房。indexPath应该由 照顾,而tableView不是细胞。理想情况下,细胞应该完全忘记它的indexPath.

始终尝试使用标准方法来解决您的问题。一般来说,当您尝试解决某些问题时,我建议您首先查看UITableView的文档,那里有很多有用的方法。

于 2018-03-02T11:30:05.987 回答
1

如果您想在用户单击单元格时获取 index path.row ,则应在用户单击时获取 index path.row ,然后将其用于您的 func

例如:

var indexrow : int = 0
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
       // table cell clicked
       indexrow = indexPath.row
    }

func cellAmountEntered(_ walletTableViewCell: WalletTableViewCell) {

     if walletTableViewCell.amountTextField.text == "" {
        return
    }
    let str = walletTableViewCell.amountTextField.text

    let crypto = cryptosArray[indexrow] 

    crypto.amount = walletTableViewCell.amountTextField.text

    //Then update array's amount value at correct index


    walletTableViewCell.amountTextField.text = ""

}
于 2018-03-02T11:45:32.620 回答