У меня есть кнопка добавления, которая добавляет текущий объект 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)
}
}