在Swift函数中访问数组的indexPath

Wiz*_*zz 1 arrays uitableview ios swift indexpath

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

我包括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 = ""

    }


}
Run Code Online (Sandbox Code Playgroud)

Mil*_*sáľ 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]
Run Code Online (Sandbox Code Playgroud)

UITableView.indexPath(for:) 文档说:

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

而这正是您想要的,您不想破坏indexPath该单元。indexPath应该由而tableView不是细胞来照顾。理想情况下,单元格应该完全忽略它indexPath

始终尝试使用标准方法来解决您的问题。通常,当您尝试解决问题时,建议您首先查看UITableView的文档,那里有许多有用的方法。