I have 2 UIButtons inside of a UICollectionViewCell, when the add button is pressed the price of the item is added to totalPrice and the button becomes hidden, and the Remove button becomes active. When the Remove button is pressed I want the price of the item to be removed from totalPrice and the Remove button to be hidden and the Add button to become active. It is for adding and removing items in a checkout flow. Right now the price subtracts and adds to totalPrice however after pressing Remove the button remains on screen. So pressing it multiple times will result in a negative number for totalPrice.
class CollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout, PostCellDelegate {
var totalPrice = Double()
private var hiddenRows = Set<Int>()
@objc func addPressed(_ sender : UIButton){
hiddenRows.insert(sender.tag)
let item = itemsArr[sender.tag].price
totalPrice += Double(item) ?? 0
sender.isHidden = true
collectionView?.reloadData()
print(item)
print(totalPrice)
}
@objc func buttonTapped(cell: PostCell) {
cell.myButton.isHidden = false
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! PostCell
let item = itemsArr[indexPath.row]
cell.delegate = self
cell.set(name: item.name, brand: item.brand, price: item.price)
cell.myButton.tag = indexPath.row
cell.removeButton.addTarget(self, action: #selector(buttonTapped(cell:)), for: .touchUpInside)
print(item)
return cell
}
protocol PostCellDelegate {
func buttonTapped(cell: PostCell)
}
class PostCell: UICollectionViewCell {
var delegate: PostCellDelegate?
let myButton: UIButton = {
let button = UIButton(type: .system)
button.titleLabel?.font = UIFont.systemFont(ofSize: 18)
button.setTitle("Add", for: .normal)
button.backgroundColor = .red
// button.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside) //here....
return button
}()
let removeButton: UIButton = {
let button = UIButton(type: .system)
button.titleLabel?.font = UIFont.systemFont(ofSize: 12)
button.setTitle("Remove", for: .normal)
return button
}()
override func prepareForReuse() {
super.prepareForReuse()
self.delegate = nil
}
func set(name: String, brand: String, price: String){
nameLabel.text = name
brandLabel.text = brand
priceLabel.text = price
}
override init(frame: CGRect) {
// self.delegate = nil
super.init(frame: frame)
self.contentView.addSubview(containerView)
containerView.addSubview(nameLabel)
containerView.addSubview(brandLabel)
containerView.addSubview(priceLabel)
containerView.addSubview(myButton)
containerView.addSubview(removeButton)
containerView.addSubview(finalLabel)
setupCellConstraints()
}
func someButtonTapped(sender: UIButton){
self.delegate?.buttonTapped(cell: self)
}