UICollectionViewCell изменяет данные, как только начинается прокрутка - PullRequest
0 голосов
/ 05 февраля 2020

У меня есть полная страница UICollectionViewCell, и как только начинается прокрутка, печатаются данные для следующего indexPath. Это вызывает проблемы в моем проекте, потому что, даже если он практически не перетаскивается, печатается следующий indexPath, и у меня внутри UICell есть кнопка UIB, которую я хочу скрыть, как только она будет нажата. Однако я только хочу, чтобы он был скрыт в указанной ячейке c. По какой-то причине он сейчас скрыт в разных индексах моего collectionView. Все поможет, спасибо.

  class CollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {


       init() {
       super.init(collectionViewLayout: UICollectionViewFlowLayout())
              }
       required init?(coder: NSCoder) {
          fatalError("init(coder:) has not been implemented")
              }

private var collectionViewFlowLayout: UICollectionViewFlowLayout {
    return collectionViewLayout as! UICollectionViewFlowLayout
}
override func viewDidLoad() {
    collectionView.showsHorizontalScrollIndicator = false
    collectionView.showsVerticalScrollIndicator = false
    collectionViewFlowLayout.minimumLineSpacing = 0

    self.collectionView.isPagingEnabled = true
    if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
        layout.scrollDirection = .horizontal
    }
    collectionView?.register(PostCell.self, forCellWithReuseIdentifier: cellId)
}

   func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
       let screenSize = UIScreen.main.bounds.size
       return screenSize

   }

      override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
                  return itemsArr.count
           }

  var totalPrice = Double()

    @objc func buttonPressed(_ sender : UIButton){
    let item = itemsArr[sender.tag].price
    totalPrice += Double(item) ?? 0
    sender.isHidden = true
    print(item)
    print(totalPrice)
}

           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.set(name: item.name, brand: item.brand, price: item.price)
    cell.myButton.tag = indexPath.row

    cell.myButton.addTarget(self, action: #selector(buttonPressed(_:)), for: .touchUpInside) 
      return cell
  }
 }

1 Ответ

2 голосов
/ 05 февраля 2020

Вам необходимо сохранить набор индексов строк, для которых кнопка скрыта. Затем при рендеринге ячейки, если этот индекс строки присутствует в hiddenRows, вы скрываете кнопку перед возвратом ячейки.

class CollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {

    private var hiddenRows = Set<Int>()

    init() {
        super.init(collectionViewLayout: UICollectionViewFlowLayout())
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private var collectionViewFlowLayout: UICollectionViewFlowLayout {
        return collectionViewLayout as! UICollectionViewFlowLayout
    }

    override func viewDidLoad() {
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.showsVerticalScrollIndicator = false
        collectionViewFlowLayout.minimumLineSpacing = 0

        self.collectionView.isPagingEnabled = true
        if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
            layout.scrollDirection = .horizontal
        }
        collectionView?.register(PostCell.self, forCellWithReuseIdentifier: cellId)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let screenSize = UIScreen.main.bounds.size
        return screenSize

    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return itemsArr.count
    }

    var totalPrice = Double()

    @objc func buttonPressed(_ sender : UIButton){
        hiddenRows.insert(sender.tag)
        let item = itemsArr[sender.tag].price
        totalPrice += Double(item) ?? 0
        sender.isHidden = true
        print(item)
        print(totalPrice)
    }

    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.set(name: item.name, brand: item.brand, price: item.price)
        cell.myButton.tag = indexPath.row
        cell.myButton.addTarget(self, action: #selector(buttonPressed(_:)), for: .touchUpInside)
           print(item)
        if hiddenRows.contains(indexPath.row) {
            cell.myButton.isHidden = true
        } else {
            cell.myButton.isHidden = false
        }

        return cell
    }
 }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...