我试图在一个函数内访问一个数组的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 = ""
}
}
而不是黑客攻击,只要求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的文档,那里有很多有用的方法。
如果你想在用户点击单元格时获得索引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 = ""
}