簡體   English   中英

UICollectionReusableView問題(可重用性問題)

[英]UICollectionReusableView Problem (reusability problem)

UICollectionReusableView

我有UICollectionView (多項選擇是允許的)內部UICollectionReusableView 當我選擇UICollectionView任何單元格時,它會更改backgroundColor = .blue並且通過overriding isSelected UICollectionCell overriding isSelected屬性來處理此選擇。 問題是當我這樣做時,滾動選擇被刪除,它顯示在其他UICollectionReusableView中的選擇。

您需要在prepareForReuse方法中設置默認顏色。 您也可以在這里查看isSelected屬性。 您還可以在UICollectionReusableView prepareForReuse中調用collectionView.reloadData()

class VC: UIViewController, UICollectionViewDelegate {

    // first arg - section, second - selected indexes
    typealias DataSource = [Int: [IndexPath]]
    var selectedRows: DataSource = [:]


    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        cell.isSelected = selectedRows[indexPath.section]?.contains(indexPath) ?? false
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let contains = selectedRows[indexPath.section]?.contains(indexPath) ?? false
        if contains {
            var current = selectedRows[indexPath.section]
            current.removeAll { $0 == indexPath }
            selectedRows[indexPath.section] = current
        } else {
            selectedRows[indexPath.section] = (selectedRows[indexPath.section] ?? []) + [indexPath]
        }
        collectionView.cellForItem(at: indexPath).isSelected = !contains
    }
}

暫無
暫無

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

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