Swift CollectionView 单元格问题

Swift CollectionViewCells Issue

抱歉,标题含糊不清,但我不完全确定是这样称呼它。我在 collection 视图中有一个 collection 视图单元格列表,这些单元格只有白色背景。我总共有 20 个单元格,我希望第一个具有青色背景,第四个具有绿色背景。我的问题是,如果列表足够大并且我滚动颜色似乎是随机的,有时顶部是 4 绿色和 2 青色,而不是只有 1 青色和 1 绿色。我认为这是由于在 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell 方法中使用了 index path.row 并根据 index[= 分配颜色21=]。我认为索引 path.row 在我滚动时会发生变化,因此当我滚动到底部时,索引 path.row 是屏幕顶部而不是列表顶部的项目。我知道这不是实现此目的的正确方法,是否可以从列表中获取 first/last 项而不是当前屏幕上的 first/last 项?有没有更好的方法来完全解决这个问题?

这是问题的简单示例 - 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
}

假设您的代码没有错误(我无法判断,因为您没有包含任何代码),看起来您应该在每个 cellForItemAt 之后调用 collectionView.reloadData()。让我知道当你这样做时会发生什么。

细胞被重复使用。确保任何 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
}

你应该设置背景颜色,不管它的位置

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

可能是因为您没有在单独的 class 中定义单元格,并使用函数 prepareForReuse() 将背景设置回白色。单元格在 collectionView 中重复使用,因此有时如果您设置数据(并且不重置它),当再次使用单元格时它会保持不变。 希望这对您有所帮助!