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中被重用,所以有时如果你设置了数据(并且不重置它),当单元格被再次使用时它将保持不变。 希望这有助于!