在函数 Swift 中访问数组的 indexPath

Posted

技术标签:

【中文标题】在函数 Swift 中访问数组的 indexPath【英文标题】:Access to array's indexPath in a function Swift 【发布时间】:2018-03-02 11:25:46 【问题描述】:

我正在尝试在函数中访问数组的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 = ""

    



【问题讨论】:

【参考方案1】:

无需破解某些东西,只需让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的文档,那里有很多有用的方法。

【讨论】:

再一次,我没有什么要补充的,除了这是米兰的完美答案,我希望我能向你上课!【参考方案2】:

如果您想在用户单击单元格时获取 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 = ""


【讨论】:

以上是关于在函数 Swift 中访问数组的 indexPath的主要内容,如果未能解决你的问题,请参考以下文章

Swift 字典内的值访问和更改(涉及数组的字典)

Swift数组中的访问结构

在 swift 4 中将数据解析为 vc 始终为零

如何使用 SWIFT 在 plist 中访问数组及其对象?

如何从 Swift 中的 void 闭包中返回一个值?

Swift 3:数组到字典?