【问题标题】:Access to array's indexPath in a function Swift在函数 Swift 中访问数组的 indexPath
【发布时间】: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 = ""

    }


}

【问题讨论】:

    标签: ios arrays swift uitableview indexpath


    【解决方案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 = ""
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多