【发布时间】:2020-07-18 15:08:25
【问题描述】:
我正在尝试使用 UICollectionViewLayout 和 UICollectionViewDiffableDataSource 创建自定义布局。 我想要一个带有单元格的部分,两个单元格都需要同时水平滚动。 但是现在我只能显示顶部的单元格,请参见下图。
这是我迄今为止尝试过的:
创建布局
func createLayout() -> UICollectionViewLayout {
let sectionProvider = { (sectionIndex: Int, layoutEnvironment: NSCollectionLayoutEnvironment) -> NSCollectionLayoutSection? in
guard let sectionKind = Section(rawValue: sectionIndex) else { return nil }
let section: NSCollectionLayoutSection
// orthogonal scrolling section of images
if sectionKind == .image {
let itemSize = NSCollectionLayoutSize(widthDimension: .absolute(self.view.frame.width), heightDimension: .fractionalHeight(0.5))
let item = NSCollectionLayoutItem(layoutSize: itemSize)
item.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0)
let groupSize = NSCollectionLayoutSize(widthDimension: .absolute(self.view.frame.width), heightDimension: .absolute(self.view.frame.height))
let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item])
section = NSCollectionLayoutSection(group: group)
section.orthogonalScrollingBehavior = .paging
section.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 0, bottom: 10, trailing: 0)
// info
} else if sectionKind == .info {
section = NSCollectionLayoutSection.list(using: .init(appearance: .sidebar), layoutEnvironment: layoutEnvironment)
section.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0)
} else {
fatalError("Unknown section!")
}
return section
}
return UICollectionViewCompositionalLayout(sectionProvider: sectionProvider)
}
配置数据源
func configureDataSource() {
// data source
dataSource = UICollectionViewDiffableDataSource<Section, Art>(collectionView: collectionView) {
(collectionView, indexPath, item) -> UICollectionViewCell? in
guard let section = Section(rawValue: indexPath.section) else { fatalError("Unknown section") }
switch section {
case .image:
return collectionView.dequeueConfiguredReusableCell(using: self.configuredGridCell(), for: indexPath, item: item)
case .info:
return collectionView.dequeueConfiguredReusableCell(using: self.configuredListCell(), for: indexPath, item: item)
}
}
}
应用初始快照
func applyInitialSnapshots() {
// set the order for our sections
let sections = Section.allCases
var snapshot = NSDiffableDataSourceSnapshot<Section, Art>()
snapshot.appendSections(sections)
dataSource.apply(snapshot, animatingDifferences: false)
// recents (orthogonal scroller)
var imageSnapshot = NSDiffableDataSourceSectionSnapshot<Art>()
imageSnapshot.append(self.arts)
dataSource.apply(imageSnapshot, to: .image, animatingDifferences: false)
var allSnapshot = NSDiffableDataSourceSectionSnapshot<Art>()
allSnapshot.append(self.arts)
dataSource.apply(allSnapshot, to: .info, animatingDifferences: false)
}
【问题讨论】:
标签: ios swift uicollectionview