0

對不起,模糊的標題,但我不完全確定要打電話給它。我有一個集合視圖中的單元格列表,這些單元格只有一個白色背景。我總共有20個單元,我希望第一個有青色背景,第四個有綠色背景。我的問題是,如果列表足夠大,我滾動的顏色似乎是隨機的,有時4綠色和2青色在頂部,而不是隻有1青色和1綠色。我認爲這是由於在func collectionView(_ collectionView:UICollectionView,cellForItemAt indexPath:IndexPath) - > UICollectionViewCell方法中使用索引path.row,並根據indexpath.row分配顏色。我認爲索引path.row在我滾動時發生變化,因此當我滾動到底部索引path.row時,屏幕頂部的項目不在列表頂部。我知道這不是實現這一目標的正確方法,無論如何,從列表中獲取第一個/最後一個項目,而不是當前在屏幕上的第一個/最後一個項目?有沒有更好的方法去完成這件事?Swift CollectionViewCells問題

這裏是什麼樣的問題,看起來像一個簡單的例子 - https://gyazo.com/e66d450e9ac50b1c9acd521c959dd067

編輯:

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int` is return 20 and in `func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell` this is what I have - `let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Invite Cell", for: indexPath) as! InviteCell 
    print(indexPath.row) 

    if indexPath.row == 0 { 
     cell.InviteCellContainer.backgroundColor = UIColor.cyan 
    } else if indexPath.row == 5 { 
     cell.InviteCellContainer.backgroundColor = UIColor.green 
    } 
    return cell 
} 

回答

2

細胞被重複使用。確保所有UI元素在cellForItemAt:

在代碼中定義的狀態狀態不定如果該行不爲0,而不是5。所以你需要添加的情況下爲所有其他指標:

if indexPath.row == 0 { 
    cell.InviteCellContainer.backgroundColor = UIColor.cyan 
} else if indexPath.row == 5 { 
    cell.InviteCellContainer.backgroundColor = UIColor.green 
} else { 
    cell.InviteCellContainer.backgroundColor = UIColor.gray // or what the default color is 
} 
return cell 

更具描述語法是switch表達

switch indexPath.row { 
    case 0: cell.InviteCellContainer.backgroundColor = UIColor.cyan 
    case 4: cell.InviteCellContainer.backgroundColor = UIColor.green 
    default: cell.InviteCellContainer.backgroundColor = UIColor.gray 
} 
+0

上添加了兩個collectionview函數中的代碼謝謝你這個修復了!!!! – XvKnightvX

0

假設你的代碼是沒有故障,我不能告訴你,因爲不包括任何一個,看起來你應該在每個cellForItemAt之後調用collectionView.reloadData()。讓我知道當你這樣做時會發生什麼。

+0

我在問題 – XvKnightvX

0

,則應該設置的背景顏色而不管其位置的

if(indexPath.row == 0) { 
    cell.InviteCellContainer.backgroundColor = UIColor.cyan 
} else if(indexPath.row == 5) { 
    cell.InviteCellContainer.backgroundColor = UIColor.green 
} else { 
    cell.InviteCellContainer.backgroundColor = UIColor.white 
} 
return cell 

這可能是因爲您尚未在單獨的類中定義單元格,並使用函數prepareForReuse()將背景設置爲白色。單元格在一個collectionView中被重用,所以有時如果你設置了數據(並且不重置它),當單元格被再次使用時它將保持不變。 希望這有助於!