我正在尝试创建一个包含多个部分的集合视图。每个部分都是全屏的并且有多个单元格。我正在使用 UICollectionViewCompositionalLayout。 collectionview 具有水平分页,您可以在其中水平地从一个部分滚动到另一个部分。每个部分都有一个带标签的标题。我对每个部分中单元格的位置有疑问。对于每个部分,我需要单元格位于部分标题的正下方。
import Foundation
import UIKit
class SetupProfileController:UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
var collectionView: UICollectionView!
let colors = [UIColor.red, UIColor.blue, UIColor.green, UIColor.orange, UIColor.purple, UIColor.red, UIColor.blue, UIColor.green, UIColor.orange, UIColor.purple]
let data:[String:[String]] = [
"Section 1":["One","Two","Three","Four","Five","Six"],
"Section 2":["Astrology","Engineers|Scientists","SoftwareDevelopers","Mathematicians","Physicists","ArtificialIntelligence","ComputerVision",
"Filmmaking","VisualArtists","Animators","Singers","SongWriters","Rappers","AfroBeats","MusicProducers","FashionDesigners","Chefs|Cooks","Drag","Performers","Dancers","Musicians","Music","MusicProducers","Animators","AnimalRightsActivists","TransMen","TransWomen","Nonbinary","Women","Men","PhDs","History","StartUps","MentalHealth","PhysicalFitness","LanguageLearning","AsylumSeekers","Environmentalism","Veganism"]
]
let sections = ["Section 1","Section 2"]
override func viewDidLoad() {
print("COLLECTIONVIEW")
let layout = makeLayout()
//self.collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height), collectionViewLayout: layout)
self.collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
//collectionView.isScrollEnabled = true
self.collectionView.register(SetupProfileTitleHeader.self, forSupplementaryViewOfKind: "header", withReuseIdentifier: "SetupProfileTitleHeader")
self.collectionView.register(CollectionViewCell.self, forCellWithReuseIdentifier: "CollectionViewCell")
self.collectionView.delegate = self
self.collectionView.dataSource = self
self.collectionView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(self.collectionView)
NSLayoutConstraint.activate([
self.collectionView.topAnchor.constraint(equalTo: self.view.layoutMarginsGuide.topAnchor),
self.collectionView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
self.collectionView.leftAnchor.constraint(equalTo: self.view.leftAnchor),
self.collectionView.rightAnchor.constraint(equalTo: self.view.rightAnchor)
])
collectionView.isPagingEnabled = true
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return sections.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return data[sections[section]]!.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell
//cell.backgroundColor = colors[indexPath.item]
cell.backgroundColor = .red
cell.textLabel.text = data[sections[indexPath.section]]![indexPath.item]
return cell
}
func makeLayout() -> UICollectionViewLayout {
//let layout = UICollectionViewCompositionalLayout { (section: Int, environment: NSCollectionLayoutEnvironment) -> NSCollectionLayoutSection? in
let layout = UICollectionViewCompositionalLayout(sectionProvider: { (sectionIndex, environment) -> NSCollectionLayoutSection? in
let itemSize = NSCollectionLayoutSize(widthDimension: .estimated(80), heightDimension: .fractionalHeight(1.0))
let item = NSCollectionLayoutItem(layoutSize: itemSize)
//item.contentInsets = NSDirectionalEdgeInsets(top: 10, leading: 10, bottom: 10, trailing: 10)
let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .absolute(40))
let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item])
group.interItemSpacing = NSCollectionLayoutSpacing.fixed(CGFloat(10))
let section = NSCollectionLayoutSection(group: group)
section.interGroupSpacing = CGFloat(10.0)
section.orthogonalScrollingBehavior = .groupPagingCentered
//section.orthogonalScrollingBehavior = .continuous
section.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 20, bottom: 0, trailing: 20)
let height = CGFloat(40)
let headerItemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension:.estimated(80) )
let headerItem = NSCollectionLayoutBoundarySupplementaryItem(layoutSize: headerItemSize, elementKind: "header", alignment: .top)
section.boundarySupplementaryItems = [headerItem]
return section
})
let config = UICollectionViewCompositionalLayoutConfiguration()
config.scrollDirection = .horizontal
config.interSectionSpacing = 0
layout.configuration = config
return layout
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
guard let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "SetupProfileTitleHeader", for: indexPath) as? SetupProfileTitleHeader else {
return SetupProfileTitleHeader()
}
headerView.titleLabel.text = "Section \(indexPath.section + 1)" //keys[indexPath.section]//"Section \(indexPath.section + 1)"
headerView.backgroundColor = .blue
return headerView
}
}
setting section.orthogonalScrollingBehavior = .groupPaging 而不是 .groupPagingCentered 似乎已经解决了这个问题