簡體   English   中英

UICollectionView-選擇隨機單元格

[英]UICollectionView - random cells are selected

我有一個水平UICollectionView,就像iOS中的水平日歷。 分頁已啟用,但不允許MultipleSelection。

self.allowsMultipleSelection = false
self.isPagingEnabled = true

每頁只有5個單元格。

 let cellSize =    CGSize(width: self.view.frame.width / 5 , height: 60)

CollectionView的高度也是60。

didSelectItemAt改變背景顏色.reddidDeselectItem重置它。白

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItem(at: indexPath)
    if let cell = cell {
        cell.backgroundColor = .red
    }
}

func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItem(at: indexPath)
    if let cell = cell {
        cell.backgroundColor = .white
    }
}

集合視圖具有多個部分和行。 如果我在第一個可見頁面中選擇一個單元格並滾動,則會在下一個可見頁面中選擇隨機單元格。 也就是說,下一頁中的隨機單元格為紅色。 我不希望這樣。 我想手動選擇/更改單元格的顏色。

我怎樣才能解決這個問題?

不要忘記UICollectionView具有嵌入式重用機制,因此您應該直接在單元格類內部的“ prepareToReuse”方法中取消選擇單元格。

取一個類級變量,比如說index

var index = -1

如您所說,不允許多項選擇,因此以下內容將為您完成工作

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    index = indexPath.item
    collectionView.reloadData()
}

func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItem(at: indexPath)
    if let cell = cell {
        cell.backgroundColor = indexPath.item == index ? .red :  .white
    }
}

每當用戶點擊任意一個單元格時,我們會將位置保存在index變量中,然后調用reloadData()通知collectionView有關更改的信息。在cellForRowAt我們檢查是否選擇了當前單元格,將顏色設置為紅色,否則設置為白色

首先,如果要保留多個選擇 ,則必須記住數組中的所選內容,因為如果回收和重復使用單元,它將丟失。 為此,請使用[IndexPath]類型)。 如果一個選定的單元格已足夠,則可以使用以下代碼的非數組版本。

var selectedItems: [IndexPath] = []

然后,在單元格的cellForItemAt(:)

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

您的didSelectItemAt委托函數應類似於:

if !selectedItems.contains(indexPath) { selectedItems.append(indexPath)}

collectionView.cellForItem(at: indexPath)?.backgroundColor = .red

和您的didDeselectItemAt委托函數:

if let index = selectedItems.firstIndex(of: indexPath) { selectedItems.remove(at: index) }

collectionView.cellForItem(at: indexPath)?.backgroundColor = .white

這實際上應該工作。 讓我知道是否需要進行調整。

暫無
暫無

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

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