首页 文章

Swift CollectionViewCells问题

提问于
浏览
0

对于模糊的 Headers 感到抱歉,但我不确定是否打电话给它 . 我在集合视图中有一个集合视图单元列表,这些单元格只有一个白色背景 . 我总共有20个单元格,我希望第一个有青色背景,第四个有绿色背景 . 我的问题是,如果列表足够大,我滚动颜色似乎是随机的有时4绿色和2青色在顶部而不是只有1青色和1绿色 . 我认为这是由于在func collectionView(_ collectionView:UICollectionView,cellForItemAt indexPath:IndexPath) - > UICollectionViewCell方法中使用索引path.row并根据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 回答

  • 2

    细胞被重复使用 . 确保 cellForItemAt: 中的任何UI元素都具有已定义的状态

    在您的代码中,如果行不是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

    假设您的代码不是't faulty, which I can'告诉,因为您没有包含任何内容,看起来您应该在每个cellForItemAt之后调用 collectionView.reloadData() . 让我知道你这样做会发生什么 .

  • 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中重复使用,因此有时如果设置数据(并且不重置它),则在再次使用单元格时它将保持不变 . 希望这可以帮助!

相关问题