簡體   English   中英

如何返回到第一個collectionview單元格項目?

[英]How do I return back to the first collectionview cell item?

我正在為移動應用程序使用UICollectionViewCell 當您點擊crossBtn它應該轉到第一個UICollectionViewCell並重新加載數據,但是collectionView?.reloadData()會使顏色混亂,並且每個單元一次都不會保持一種顏色。 相反,即使我在didDeselectItemAt方法中將顏色設置為UIColor.clear ,它仍然在單元格上顯示多種顏色。

當用戶在不重新加載整個UICollectionView情況下輕按crossBtn時,如何返回第一個UICollectionViewCell項?

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

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

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {


        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CollectionViewCell

        cell.hamburgerLabel.text = filters[indexPath.item]

//        cell.hamburgerImageView.image = filterImages[indexPath.item]

        return cell
    }


func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItem(at: indexPath)
    cell?.layer.backgroundColor = UIColor.gray.cgColor
    setFilter(title: filterNames[indexPath.row])
    toolBar.isHidden = true
    yesAndNoToolBar.isHidden = false
}

func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItem(at: indexPath)
    cell?.layer.backgroundColor = UIColor.clear.cgColor
    collectionView.deselectItem(at: indexPath, animated: true)
}


@IBAction func crossBtn(_ sender: UIBarButtonItem) {
    toolBar.isHidden = false
    yesAndNoToolBar.isHidden = true

    collectionView?.reloadData()

    let indexPath = self.collectionView.indexPathsForSelectedItems?.last ?? IndexPath(item: 0, section: 0)
    self.collectionView.selectItem(at: indexPath, animated: false, scrollPosition: UICollectionViewScrollPosition.centeredVertically)

}

您可能不必重新加載數據。 您可以使用以下方法滾動到給定的索引路徑。

let indexPath = self.collectionView.indexPathsForSelectedItems?.last ?? IndexPath(item: 0, section: 0)
func scrollToItem(at indexPath: indexPath, 
               at scrollPosition: .centeredVertically, 
         animated: true)

請注意,這與使用selectItem(at:animated:scrollPosition:)

另外,您應該在cellForItem方法中而不是在選擇和取消選擇委托方法中設置遇到問題的顏色等。 這是因為單元格已被重用,所以在滾動時,您正在設置樣式的單元格將在其他位置使用。 而是使用選擇和取消選擇方法將所選索引路徑存儲在變量(或多個數組)中,然后在cellForItem檢查此數組以確定是否將所選樣式應用於該單元格。 這就是為什么collectionView.reloadData()為您搞砸的原因!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM