在函数Swift中访问数组的indexPath

问题描述 投票:1回答:2

我试图在一个函数内访问一个数组的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 = ""

    }


}
ios arrays swift uitableview indexpath
2个回答
4
投票

而不是黑客攻击,只要求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:) documentation说:

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

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

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


1
投票

如果你想在用户点击单元格时获得索引path.row,你应该在用户点击时获得索引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 = ""

}
© www.soinside.com 2019 - 2024. All rights reserved.