【问题标题】:How to set background color in cell section not header section?如何在单元格部分而不是标题部分设置背景颜色?
【发布时间】:2019-12-11 08:33:49
【问题描述】:

我创建了一个collectionView并想设置单元格部分背景颜色

因为我不知道它有多少行,我不想在其他部分设置背景颜色

设置整个单元格部分的背景颜色

【问题讨论】:

  • 我相信您必须在 cellForRowAt 方法中分别为每个单元格设置背景颜色,您将检查 indexPath.section == 是否设置相应的颜色。
  • iOS 13+ -> UICollectionViewCompositionalLayout
  • collectionViewCell 中有什么? ,好像该元素覆盖了所有区域,那么cell.backgroundColor 将不会出现......否则@Aaira Samson 的答案应该可以工作......
  • stackoverflow.com/a/34697261/7316675 这可能对你有帮助

标签: ios swift uicollectionview uicolor


【解决方案1】:

您可以在自己的 cellForItemAt 上执行此操作,希望对您有所帮助 :)

func collectionView(_ collectionView: UICollectionView,
                    cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! SampleCell
    if indexPath.section == 1 {
        cell.backgroundColor = UIColor.systemPink
    } else {
        cell.backgroundColor = UIColor.white
    }
    return cell
}

【讨论】:

    【解决方案2】:

    您可以使用以下代码:

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! TestCell
    
            if indexPath.section == 1 {
    
               cell.backgroundColor = UIColor.red
    
            } else {
    
               cell.backgroundColor = UIColor.orange
    
            }
    
            return cell
    
         }
    

    【讨论】:

      【解决方案3】:

      我终于找到了解决办法。

      cell中有两个UIView,分别是cell View和contentView。您添加的所有视图都在 contentView 中。所以我应该:

      • 设置单元格背景颜色
      • 添加一个层,该层由单元框插入框架
      • 设置图层背景颜色
      • 添加视图

      【讨论】:

        猜你喜欢
        • 2012-01-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-19
        • 2023-03-04
        • 2011-06-13
        • 2014-07-08
        • 2011-08-30
        相关资源
        最近更新 更多