У меня есть 2 кнопки UIB внутри UICollectionViewCell, при нажатии кнопки добавления цена элемента добавляется к totalPrice, и кнопка становится скрытой, а кнопка удаления становится активной. Когда нажата кнопка «Удалить», я хочу, чтобы цена элемента была удалена из totalPrice, и кнопка «Удалить» была скрыта, а кнопка «Добавить» стала активной. Он предназначен для добавления и удаления товаров в процессе оформления заказа. Прямо сейчас цена вычитается и прибавляется к итоговой цене, однако после нажатия кнопки «Удалить» кнопка остается на экране. Таким образом, нажатие на него несколько раз приведет к отрицательному числу для 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)
}