首页 > 解决方案 > 点击按钮时如何从数组中删除元素

问题描述

我有一个添加按钮,可将当前 Item 对象添加到 finalList 数组。我正在尝试实现删除按钮以从同一数组中删除该当前项目(如果已添加)。这些项目与添加和删除按钮一起位于整页 UICollectionViewCell 上。

   var finalList = [Item]()
    private var hiddenRows = Set<Int>()
@objc func addTapped(cell: PostCell) {

      guard let indexPath = self.collectionView.indexPath(for: cell)  else {return}
      hiddenRows.insert(indexPath.row)
      cell.removeButton.isHidden = false

      let item = itemsArr[indexPath.row]

  //  cell.currentPrice += Float(item.price) ?? 0

    finalList.append(item)
    collectionView?.reloadData()
      totalPrice += Float(item.price) ?? 0
    cell.finalLabel.text = String(cell.currentPrice)

       }


@objc func removeButtonTapped(cell: PostCell) {
    guard let indexPath = self.collectionView.indexPath(for: cell)  else {return}
    hiddenRows.insert(indexPath.row)
    cell.myButton.isHidden = false
    let item = itemsArr[indexPath.row]

  //  finalList.remove(at: item.)
    totalPrice -= Float(item.price) ?? 0
    cell.currentPrice -= Float(item.price) ?? 0
    cell.finalLabel.text = String(cell.currentPrice)
 //   collectionView?.reloadData()
     }

  extension CollectionViewController {

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 0
}

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return itemsArr.count
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! PostCell

            cell.delegate = self

      let item = itemsArr[indexPath.row]
    let page = itemsArr[indexPath.item]
    cell.set(name: item.name, brand: item.brand, price: item.price)

    print(finalList)
     if hiddenRows.contains(indexPath.row) {

                cell.myButton.isHidden = true
                cell.removeButton.isHidden = false
            }else{
                cell.removeButton.isHidden = true
                cell.myButton.isHidden = false
            }



    return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: view.frame.width, height: view.frame.height)
}

}

标签: iosarraysswift

解决方案


你需要一个独特的钥匙假设它的名字

finalList.removeAll { $0.name == item.name }

在删除不要使用insert而不是使用

hiddenRows.removeAll { $0 == indexPath.row }  

推荐阅读