UICollectionView - random cells are selected

后端 未结 3 1984
北海茫月
北海茫月 2021-01-23 12:08

I have a Horizontal UICollectionView like the horizontal Calender in iOS. Paging is enabled but not allowsMultipleSelection.

self.allowsMultipleSelection = fals         


        
3条回答
  •  抹茶落季
    2021-01-23 12:25

    First, if you want to preserve multiple selection, you have to remember your selected ones in an array since it would get lost if a cell gets recycled and reused. For that use something like a [IndexPath] type). If one selected cell is enough, you could use a non-array version of below code.

    var selectedItems: [IndexPath] = []
    

    Then, do your recoloring in your cell's cellForItemAt(:):

    cell.backgroundColor = selectedItems.contains(indexPath) ? .red : .white
    

    Your didSelectItemAt delegate function should look like:

    if !selectedItems.contains(indexPath) { selectedItems.append(indexPath)}
    
    collectionView.cellForItem(at: indexPath)?.backgroundColor = .red
    

    and your didDeselectItemAt delegate function:

    if let index = selectedItems.firstIndex(of: indexPath) { selectedItems.remove(at: index) }
    
    collectionView.cellForItem(at: indexPath)?.backgroundColor = .white
    

    This should actually work. Let me know if we have to do adjustments.

提交回复
热议问题