У меня есть "totalPrice" UILabel
внутри полной страницы UICollectionViewCell
. Когда я нажимаю кнопку добавления, предполагается добавить цену указанного элемента c на ярлык totalPrice для этих ячеек. И когда я нажимаю вычитать, это вычитает общую стоимость. По какой-то причине третья или иногда четвертая ячейка отображают неверную общую цену. Мои логики c неверны, но я не могу точно определить, в чем именно заключается проблема.
class CollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout, PostCellDelegate {
var totalPrice = Float()
private var hiddenRows = Set<Int>()
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
var totalPrice = Float()
private var hiddenRows = Set<Int>()
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! PostCell
cell.finalLabel.text = String(totalPrice)
cell.delegate = self
let item = itemsArr[indexPath.row]
cell.set(name: item.name, brand: item.brand, price: item.price)
if hiddenRows.contains(indexPath.row) {
cell.myButton.isHidden = true
cell.removeButton.isHidden = false
}else{
cell.removeButton.isHidden = true
cell.myButton.isHidden = false
}
cell.finalLabel.text = String(totalPrice)
return cell
}
@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]
print(item.price)
totalPrice += Float(item.price) ?? 0
cell.finalLabel.text = String(totalPrice)
}
@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]
totalPrice -= Float(item.price) ?? 0
cell.finalLabel.text = String(totalPrice)
// collectionView?.reloadData()
}
}
protocol PostCellDelegate {
func removeButtonTapped(cell: PostCell)
func addTapped(cell: PostCell)
func didPressButton(_ tag: Int)
}
class PostCell: UICollectionViewCell {
var delegate: PostCellDelegate?
func set(name: String, brand: String, price: String){
nameLabel.text = name
brandLabel.text = brand
priceLabel.text = price
}
override init(frame: CGRect) {
super.init(frame: frame)
self.myButton.addTarget(self, action: #selector(addButtonTapped(sender:)), for: .touchUpInside)
self.removeButton.addTarget(self, action: #selector(subButtonTapped(sender:)), for: .touchUpInside)
setupCellConstraints()
}
@objc func buttonPressed(_ sender: UIButton) {
delegate?.didPressButton(sender.tag)
}
@objc func addButtonTapped(sender: UIButton){
self.delegate?.addTapped(cell: self)
sender.isHidden = true
}
@objc func subButtonTapped(sender: UIButton){
self.delegate?.removeButtonTapped(cell: self)
sender.isHidden = true
}
}