ios Swift -如何在CompositionalLaylout中更改组的BackgroundColor [关闭]

tv6aics1  于 2023-08-08  发布在  iOS
关注(0)|答案(1)|浏览(123)

已关闭。此问题需要更多focused。它目前不接受回答。
**希望改进此问题?**更新问题,使其仅针对editing this post的一个问题。

5天前关闭。
Improve this question
我目前正在开发一个消息应用程序,并使用组合布局来创建Element/What's App的“新聊天”功能。我的问题是,我想改变我的组的背景颜色,就像在什么是应用程序。我已经设法改变了部分的背景颜色,但这是太多了。
我把一个例子从什么是应用程序在它应该如何看。
有谁能告诉我,我必须添加什么,才能得到这个?
找不到任何关于组backgroundcolor在互联网What's app example - image我的代码:

private func initCollectionView() {
        
        let layout = UICollectionViewCompositionalLayout { (sectionIndex, layoutEnvironment) -> NSCollectionLayoutSection? in
            let section = self.dataSource.snapshot().sectionIdentifiers[sectionIndex]
            
            switch section {
            case .localContacts:
                return self.listStyleSection(layoutEnvironment: layoutEnvironment)
                
            case .matrixContacts:
                return self.listStyleSection(layoutEnvironment: layoutEnvironment)
                
            case .ADContacts:
                return self.galleryStyleSection(layoutEnvironment: layoutEnvironment, height: 0.3, width: 0.3, space: 20.0, itemPerLine: 2)
            }
        }
        
        self.collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        
        self.view.addSubview(self.collectionView)
        
        self.collectionView.constrain(toBeBelow: self.adButton, padding: .exact(10))
        self.collectionView.constrain(toHorizontalBoundsOf: self.view)
        self.collectionView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
        
        self.initDataSource()
        self.collectionView.dataSource = self.dataSource
        self.collectionView.delegate = self
        
    
    }```
private func initDataSource() {
    
    dataSource = UICollectionViewDiffableDataSource<ContactSections, ContactEntry>(collectionView: collectionView) {
        (collectionView, indexPath, item) -> UICollectionViewCell? in
        
        return self.configureCell(collectionView: collectionView, indexPath: indexPath, item: item)
        
    }
    
    // Registrieren Sie die Zellen für jede Sektion
    collectionView.register(ContactCell.self, forCellWithReuseIdentifier: "ContactIdentifier")
    collectionView.register(ADCell.self, forCellWithReuseIdentifier: "ADIdentifier")
    collectionView.register(ContactCell.self, forCellWithReuseIdentifier: "MXIdentifier")
    

    //swift-format-ignore
    collectionView.register(CustomHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "header")
    //swift-format-ignore
    collectionView.register(CustomFooter.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "footer")
    
    
    self.dataSource.supplementaryViewProvider = { [unowned self] collectionView, kind, indexPath in
        return self.supplementary(collectionView: collectionView, kind: kind, indexPath: indexPath)
    }
}
func supplementary(collectionView: UICollectionView, kind: String, indexPath: IndexPath) -> UICollectionReusableView? {
    //swift-format-ignore
    if kind == UICollectionView.elementKindSectionHeader {
        let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "header", for: indexPath) as! CustomHeader
        header.titleLabel.text = self.dataSource.snapshot().sectionIdentifiers[indexPath.section].textRepresentation
        header.isButtonAllShownActive = false
        return header
        
    } else if kind == UICollectionView.elementKindSectionFooter {
        //swift-format-ignore
        let footer = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "footer", for: indexPath) as! CustomFooter
        return footer
    }
    return UICollectionReusableView()
    
}
func configureCell(collectionView: UICollectionView, indexPath: IndexPath, item: ContactEntry) -> UICollectionViewCell {
    let section = self.dataSource.snapshot().sectionIdentifiers[indexPath.section]
    
    switch section {
    case .localContacts:
        return self.configureLocalContactCell(item: item, indexPath: indexPath)
        
    case .matrixContacts:
        return self.configureMXContactCell(item: item, indexPath: indexPath)
        
    case .ADContacts:
        return self.configureADContactCell(item: item, indexPath: indexPath)
    }
}
private func configureMXContactCell(item: ContactEntry, indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MXIdentifier", for: indexPath) as! ContactCell
    
    var contentConfiguration = ContactContentConfiguration()

    contentConfiguration.displayName = item.contact!.givenName + " " + item.contact!.familyName
    
    cell.contentConfiguration = contentConfiguration
    
    return cell
}
private func configureLocalContactCell(item: ContactEntry, indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ContactIdentifier", for: indexPath) as! ContactCell
    
    var contentConfiguration = ContactContentConfiguration()

    contentConfiguration.displayName = item.contact!.givenName + " " + item.contact!.familyName
    

    
    cell.contentConfiguration = contentConfiguration
    
    return cell
}
private func configureADContactCell(item: ContactEntry, indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ADIdentifier", for: indexPath) as! ADCell
    
    var contentConfiguration = ADContentConfiguration(title: item.adContact!.name!, logo: UIImage(systemName: "person.fill")!)

    cell.contentConfiguration = contentConfiguration
    
    return cell
}
func galleryStyleSection(layoutEnvironment: NSCollectionLayoutEnvironment, height: CGFloat = 0.5, width: CGFloat = 0.5, space: CGFloat = 10.0, itemPerLine: Int = 2) -> NSCollectionLayoutSection {
    
    let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(width), heightDimension: .fractionalHeight(1.0))
    let item = NSCollectionLayoutItem(layoutSize: itemSize)
    
    let groupSize: NSCollectionLayoutSize
    
    groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .fractionalWidth(height))
    
    let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitem: item, count: itemPerLine)
    group.interItemSpacing = .fixed(space)
    
    let header = self.generateHeader()
    let footer = self.generateFooter()
    
    let sec = NSCollectionLayoutSection(group: group)
    sec.interGroupSpacing = space
    sec.contentInsets = NSDirectionalEdgeInsets(top: 10, leading: 20, bottom: 15, trailing: 20)
   
        sec.boundarySupplementaryItems = [header]
    
    
    return sec
    
}
func generateHeader() -> NSCollectionLayoutBoundarySupplementaryItem {
    let headerSize = NSCollectionLayoutSize(
        widthDimension: .fractionalWidth(1.0),
        heightDimension: .absolute(40.0))
    let header = NSCollectionLayoutBoundarySupplementaryItem(
        layoutSize: headerSize,
        elementKind: UICollectionView.elementKindSectionHeader,
        alignment: .top)
    
    return header
}
func generateFooter(height: CGFloat? = nil) -> NSCollectionLayoutBoundarySupplementaryItem {
    let footsize: NSCollectionLayoutSize
    
    if height == nil {
        footsize = NSCollectionLayoutSize(
            widthDimension: .fractionalWidth(1.0),
            heightDimension: .absolute(30.0))
    } else {
        footsize = NSCollectionLayoutSize(
            widthDimension: .fractionalWidth(1.0),
            heightDimension: .absolute(height!))
    }
    
    
    let footer = NSCollectionLayoutBoundarySupplementaryItem(
        layoutSize: footsize,
        elementKind: UICollectionView.elementKindSectionFooter,
        alignment: .bottom)
    return footer
}
func listStyleSection(layoutEnvironment: NSCollectionLayoutEnvironment) -> NSCollectionLayoutSection {
    
    
    let header = self.generateHeader()
    
    
    var listStyle = UICollectionLayoutListConfiguration(appearance: .plain)
    
    let sec = NSCollectionLayoutSection.list(using: listStyle, layoutEnvironment: layoutEnvironment)
    sec.contentInsets = NSDirectionalEdgeInsets(top: 10, leading: 10, bottom: 10, trailing: 10)
    
    
    sec.boundarySupplementaryItems = [header]
    
 
    header.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 10, bottom: 0, trailing: 10)
    
    
    return sec
}
hlswsv35

hlswsv351#

有太多的代码需要阅读。所以我得到的是你想要像WhatsApp在背景中提供的列表,并在它后面有一个背景颜色。出于这个目的,我认为你的方法太复杂了,因为我看到你在使用UICollectionLayoutListConfiguration(appearance: .plain)并添加contentInsets,而你可以使用其他类型的外观。您应该简单地使用列表配置为所有部分,您可以创建UIcollectionViewListCell为每个部分,并根据屏幕的宽度自定义它们,甚至可以输入图像,因为单元格将基于此调整大小。这只是我会做的事情,以获得像你分享的图片中的布局:

class ViewController: UIViewController {

    @IBOutlet weak var collectionView: UICollectionView!
    
    enum Section: String, CaseIterable {
        case section1 = "Section 1"
        case section2 = "Section 2"
        case section3 = "Section 3"
    }
    
    struct SectionItem: Hashable {
        let uuid = UUID()
        let text: String
    }
    
    private var dataSource: UICollectionViewDiffableDataSource<Section, SectionItem>!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        configureCollectionView()
        configureDatasource()
        generateInitialData(animated: true)
    }
    
    // MARK: - Setup CollectionView
    private func configureCollectionView() {
        collectionView.collectionViewLayout = generateLayout()
        collectionView.delegate = self
    }

    private func generateLayout() -> UICollectionViewLayout {
        let layout = UICollectionViewCompositionalLayout { (sectionIndex: Int,
        layoutEnvironment: NSCollectionLayoutEnvironment) -> NSCollectionLayoutSection? in
            var config = UICollectionLayoutListConfiguration(appearance: .insetGrouped)
            config.headerMode = .supplementary
            config.backgroundColor = .purple.withAlphaComponent(0.25)
            return .list(using: config, layoutEnvironment: layoutEnvironment)
        }
        
        return layout
    }
    
    // MARK: - Datasource
    private func configureDatasource() {
        // list cell
        let cellRegistration = UICollectionView.CellRegistration<UICollectionViewListCell, SectionItem> { (cell, indexPath, item) in
            var contentConfiguration = UIListContentConfiguration.cell()
            contentConfiguration.text = item.text
            cell.contentConfiguration = contentConfiguration
        }
        
        // data source
        dataSource = UICollectionViewDiffableDataSource<Section, SectionItem>(collectionView: collectionView) {
            (collectionView, indexPath, item) -> UICollectionViewListCell? in
            return collectionView.dequeueConfiguredReusableCell(using: cellRegistration, for: indexPath, item: item)
        }
        
        // header r
        let headerRegistration = UICollectionView.SupplementaryRegistration
        <SimpleHeaderView>(elementKind: UICollectionView.elementKindSectionHeader) {
            (supplementaryView, string, indexPath) in
            supplementaryView.configure(with: Section.allCases[indexPath.section].rawValue)
        }
        
        dataSource.supplementaryViewProvider = { (view, kind, indexPath) in
            return self.collectionView.dequeueConfiguredReusableSupplementary(
                using: headerRegistration, for: indexPath)
        }
    }
    
    private func generateInitialData(animated: Bool) {
        var snapshot = NSDiffableDataSourceSnapshot<Section, SectionItem>()
        
        let sections = Section.allCases
        snapshot.appendSections(sections)
        
        for item in 0...3 {
            snapshot.appendItems([SectionItem(text: "\(item)")], toSection: .section1)
        }
        
        for item in 0...4 {
            snapshot.appendItems([SectionItem(text: "\(item)")], toSection: .section2)
        }
        
        for item in 0...2 {
            snapshot.appendItems([SectionItem(text: "\(item)")], toSection: .section3)
        }
        
        dataSource.apply(snapshot, animatingDifferences: animated)
    }

}

字符串
看起来是这样的:

的数据
您可以根据需要修改此代码以创建布局。只要确保创建的单元子类为UIcollectionViewListCell,而不是UICollectionViewCell,如果你使用的是List。您甚至可以修改默认提供的这个单元格子类,它非常可定制,并使用contentConfiguration.image添加图像,这将在左侧添加图像,您可以根据您的需求自定义甚至使用不同类型的列表单元格配置,如UIListContentConfiguration.valueCell()

let cellRegistration = UICollectionView.CellRegistration<UICollectionViewListCell, SectionItem> { (cell, indexPath, item) in
            var contentConfiguration = UIListContentConfiguration.cell()
            contentConfiguration.text = item.text
            cell.contentConfiguration = contentConfiguration
        }

相关问题