【问题标题】:indexPath of UICollectionView change when I scroll down向下滚动时 UICollectionView 的 indexPath 发生变化
【发布时间】:2020-04-18 14:43:05
【问题描述】:

我有简单的 CollectionView,我需要将索引 1 处的背景单元格设置为绿色,启动时可以(看图片)

但是在我向下和向后滚动后,我有很多绿色单元格? 我该怎么办?

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {[enter image description here][1]
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! MessageCollectionViewCell
    cell.textMessageLabel.text = arrMes[indexPath.row].textMessage
    cell.dataMessage.text = arrMes[indexPath.row].dataOfMessage

    if indexPath.row == 1 {
        cell.backgroundColor = .green
    }
    return cell
}

【问题讨论】:

    标签: ios swift xcode indexing uicollectionview


    【解决方案1】:

    单元被重复使用 - 因此调用dequeueReusableCell()

    因此,您需要将背景设置为默认颜色:

    if indexPath.row == 1 {
        cell.backgroundColor = .green
    } else {
        cell.backgroundColor = .white // or whatever your "default" color should be
    }
    

    编辑 (评论后)

    既然您正在显示“消息”......请考虑一个“聊天”应用程序。消息可能是“来自”某人或“给”某人。我假设您的数据已经知道这一点,因此您可以这样做:

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! MessageCollectionViewCell
    
        cell.textMessageLabel.text = arrMes[indexPath.row].textMessage
        cell.dataMessage.text = arrMes[indexPath.row].dataOfMessage
    
        if arrMes[indexPath.row].fromOrTo == "from" {
            cell.backgroundColor = .green
        } else {
            cell.backgroundColor = .yellow
        } 
    
        return cell
    }
    

    【讨论】:

    • 谢谢,但我的问题远不止于此。如果我需要为每个单元格设置独特的内容怎么办?你能帮帮我吗?
    • @DonMag ,非常感谢,它有帮助)
    【解决方案2】:

    当您向下滚动时,集合视图正在重用这些单元格,这就是为什么您可以看到更多带有绿色背景的单元格。要解决此问题,您需要为不在索引 1 处的其他单元格设置背景颜色。 因此,例如,您可以使用以下方法更新您的函数:

    if indexPath.row == 1 {
        cell.backgroundColor = .green
    } else {
        cell.backgroundColor = .white // your desired color
    }
    

    或更短的可能性:

     cell.backgroundColor = indexPath.row == 1 ? .green : .white
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      相关资源
      最近更新 更多