UILabel внутри UICollectionViewCell не обновляется правильно - PullRequest
1 голос
/ 08 февраля 2020

У меня есть "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 
    }
}

Ответы [ 2 ]

1 голос
/ 08 февраля 2020

Вы должны удалить переменные totalPrice и hiddenRows в функции cellForItem, может быть, вы можете вывести ее наружу, но не там. Поскольку он всегда вызывается всякий раз, когда ячейка будет отображаться, то есть она вернется к своему начальному значению как пустому.

А также, если вы хотите, чтобы ваш tableView отражал ваши новые данные, источником данных должен быть обновлен для табличного представления, чтобы отразить его данные. Никогда не изменяйте свойства ячейки в одиночку, потому что она может быть использована повторно. Надеюсь, это поможет.

0 голосов
/ 09 февраля 2020

Это из-за повторного использования ячейки удалить общую цену

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    // remove this line
    //var totalPrice = Float()

    private var hiddenRows = Set<Int>()

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! PostCell
    //remove this line
    //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
    }
    // remove this line
    //cell.finalLabel.text = String(totalPrice)
    return cell

}

сохранить текущую цену в ячейке

class PostCell: UICollectionViewCell {
 var currentPrice: Float = 0
 var delegate: PostCellDelegate?
 func set(name: String, brand: String, price: String){
     nameLabel.text = name
     brandLabel.text = brand
     priceLabel.text = price
     finalLabel.text = "\(currentPrice)"
 }

. , .

}

Вычислить текущую цену

@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)
  cell.currentPrice += 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]
cell.currentPrice -= Float(item.price) ?? 0
  cell.finalLabel.text = String(cell.currentPrice)
}
...