如何在UICollectionView中更改整个部分的背景颜色?

lic*_*853 30 background-color ios uicollectionview

在UICollectionView中,我想给整个部分一个统一的背景颜色,而不是单个单元格或整个集合视图.

我没有看到任何委托方法,任何建议?

小智 15

首先,将 UICollectionReusableView 作为背景视图。我只是将我的设置为红色。

class SectionBackgroundDecorationView: UICollectionReusableView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = .red
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,在 YourCollectionViewController 中:

static let background = "background-element-kind"

init() {
    super.init(collectionViewLayout: YourCollectionViewController.createLayout())
}

static func createLayout() -> UICollectionViewLayout {
    let layout = UICollectionViewCompositionalLayout { (sectionIndex: Int,
        layoutEnvironment: NSCollectionLayoutEnvironment) -> NSCollectionLayoutSection? in
        
        // Use sectionIndex to control the layout in each section
        if sectionIndex == 0 {
            
            // Customise itemSize, item, groupSize, group to be whatever you want
            let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1),
                                                  heightDimension: .fractionalHeight(1))
            let item = NSCollectionLayoutItem(layoutSize: itemSize)
       
            let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1),
                                                   heightDimension: .absolute(170))
            let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item])

            let section = NSCollectionLayoutSection(group: group)
            
            // Create a sectionBackground
            let sectionBackground = NSCollectionLayoutDecorationItem.background(
                    elementKind: background)

            section.decorationItems = [sectionBackground]
            return section
            
        } else {
            
          // Your layout for other sections, etc
          // You don't have to set a background for other sections if you don't want to
        }
    }
    layout.register(SectionBackgroundDecorationView.self, forDecorationViewOfKind: background)
    return layout
}
Run Code Online (Sandbox Code Playgroud)

这些文档链接对我有帮助:

  • 有没有办法根据sectionData为不同的部分提供不同的背景颜色? (2认同)

lea*_*vez 12

iOS 13 中引入的新属性有一个名为“方便添加装饰项”的UICollectionViewCompositionalLayout属性,您可以使用该属性为该部分添加背景。decorationItems

let section = NSCollectionLayoutSection(group: group)
section.decorationItems = [
   NSCollectionLayoutDecorationItem.background(elementKind:"your identifier")
]
Run Code Online (Sandbox Code Playgroud)


rde*_*mar 2

我还没有尝试过这一点,但在我看来,如果您想要单元格后面有背景(例如“图书”应用程序中的书架),则需要使用装饰视图。我认为您应该能够为每个部分拥有不同的视图,并使用委托方法设置它们layoutAttributesForDecorationViewOfKind:atIndexPath: