【问题标题】:Add or remove objects from an array based on didSelectRowAtIndexpath in Swift 3在 Swift 3 中基于 didSelectRowAtIndexpath 从数组中添加或删除对象
【发布时间】:2018-01-13 16:41:10
【问题描述】:

我正在开发可扩展的 tableView,我需要在其中添加或删除基于 didSelectRowAtIndexpath 的对象。我能够将所选项目添加到数组中,但问题是当我尝试从数组中删除选择时。

这是我得到的错误:

无法使用 (of:any) 类型的参数列表调用索引

这是我的代码:

func expandableTableView(_ expandableTableView: LUExpandableTableView, didSelectRowAt indexPath: IndexPath) {
    let selectedService = arrData[indexPath.section].Children?[indexPath.row].EnglishName ?? ""
    let inPrice = arrData[indexPath.section].Children?[indexPath.row].InPrice ?? 0

    print("service and price : \(selectedService) \(inPrice)")

    let selectedItem = (" \(selectedService) \(inPrice)")
    let cell: UITableViewCell? = expandableTableView.cellForRow(at: indexPath)

    if cell?.accessoryType == UITableViewCellAccessoryType.none
    {
        cell?.accessoryType = UITableViewCellAccessoryType.checkmark
        selectionArr.append(selectedItem)
    }
    else
    {
        cell?.accessoryType = UITableViewCellAccessoryType.none
        selectionArr.remove(at: selectionArr.index(of: selectedItem)!)
    }

    print(selectionArr)
}

【问题讨论】:

  • selectionArr是什么类型?
  • var selectionArr = [Any]()
  • [Any] 导致问题。将selectionArr 声明为更具体的内容。它似乎是一个字符串数组,所以[String].

标签: ios arrays swift uitableview swift3


【解决方案1】:

@AnhPham

嘿,尝试修改您的代码并且效果很好,请通过以下操作在数组中添加项目并分别从 tableview 的 didselect 和 diddeselect 方法中删除。

 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let categoryTableCell = self.categoriesTableview.cellForRow(at: indexPath) as! CategoriesTableCell

    self.tempCategories.append(self.categories[indexPath.row])

    print("tempArray select:\(self.tempCategories)")

}

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {

    let categoryTableCell = self.categoriesTableview.cellForRow(at: indexPath) as! CategoriesTableCell

    self.tempCategories.remove(at: self.tempCategories.index(of:self.categories[indexPath.row])!)

    print("tempArray deselect:\(self.tempCategories)")

}

【讨论】:

    【解决方案2】:

    selectionArr.remove(at: selectionArr.index(of: selectedItem)!)

    selectedItem 不是 Int。你应该会收到一个错误:

    “无法将 'String' 类型的值转换为预期的参数类型 'Int'”

    也许你只是在搜索这个:

    selectionArr.remove(at: indexPath.row)
    

    【讨论】:

    • 它工作正常,但在某个时间点索引超出范围并导致错误“致命错误:索引超出范围”,
    • 我们不是基于 indexpath.row 将对象添加到数组中,当我们尝试基于 indexpath.row 删除对象时,它会进入异常为“索引超出范围”
    • 当然你必须确保 cellsInSection 返回你的array.count 的数量,否则你的数组中与视图中的项目相关的项目数量当然与另一个数组不匹配......删除的答案很好。您应该使用一些打印来获取它...或提供更多具有相关功能的代码
    【解决方案3】:

    使用 indexPath.row 代替 selectedItem selectionArr.remove(at: selectionArr.index(of: indexPath.row)!)

    【讨论】:

      猜你喜欢
      • 2017-04-13
      • 1970-01-01
      • 1970-01-01
      • 2023-04-11
      • 1970-01-01
      • 2022-08-20
      • 2015-06-19
      • 2020-04-15
      • 2014-12-31
      相关资源
      最近更新 更多