Swift CollectionViewCells问题

时间:2017-03-01 18:18:41

标签: swift xcode uicollectionview uicollectionviewcell nsindexpath

对于模糊的标题感到抱歉,但我不能完全确定是要打电话给它。我在集合视图中有一个集合视图单元列表,这些单元格只有一个白色背景。我总共有20个单元格,我希望第一个有青色背景,第四个有绿色背景。我的问题是如果列表足够大并且我滚动颜色似乎是随机的,有时4绿色和2青色在顶部而不是仅1青色和1绿色。我认为这是由于在func collectionView中使用索引path.row(_ collectionView:UICollectionView,cellForItemAt indexPath:IndexPath) - > UICollectionViewCell方法并根据indexpath.row分配颜色。我认为当我滚动到滚动到底部索引路径时,索引path.row会发生变化。所以屏幕顶部的项目不是列表的顶部。我知道这不是实现这一目标的正确方法,无论如何从列表中获取第一个/最后一个项目而不是当前在我的屏幕上的第一个/最后一个项目?有没有更好的方法来解决这个问题?

以下是问题所在的快速示例 - 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
}

3 个答案:

答案 0 :(得分: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
}

答案 1 :(得分:0)

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

答案 2 :(得分: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中重复使用,因此有时如果您设置数据(并且不重置它),则在再次使用单元格时它将保持不变。 希望这有帮助!

相关问题