对不起,模糊的标题,但我不完全确定要打电话给它。我有一个集合视图中的单元格列表,这些单元格只有一个白色背景。我总共有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
}
上添加了两个collectionview函数中的代码谢谢你这个修复了!!!! – XvKnightvX