ios - 点击按钮时如何从数组中删除元素
问题描述
我有一个添加按钮,可将当前 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)
}
}
解决方案
你需要一个独特的钥匙假设它的名字
finalList.removeAll { $0.name == item.name }
在删除不要使用insert
而不是使用
hiddenRows.removeAll { $0 == indexPath.row }
推荐阅读
- java - 为什么 Object 类有方法 wait() 和 notify() 而 Class 类没有?
- visual-studio - Visual Studio 2015 IIS Express 不加载 CSS、JS、图像等资产
- javascript - Gulp:调用一个异步函数,该函数在转换函数中提供自己的回调
- kubernetes - 服务(NodePort)间歇性超时
- java - Websphere 9:Workmanager 中的 Jax-WS 调用第二次失败
- python - Python字符串正则表达式联合返回一堆空字符串
- django - 单击 django 博客卡中的阅读更多按钮后,尝试在新的 html 页面上显示完整的博客
- azure-cli - 使用 Azure CLI 和 JMESPath 进行筛选
- mongodb - mongodb的安装破坏了我的包管理器
- mysql - Mysql嵌套并声明为数组