这是我的课:
class MediaViewController: UIViewController{
var collectionView: UICollectionView! = nil
private lazy var dataSource = makeDataSource()
fileprivate typealias DataSource = UICollectionViewDiffableDataSource<SectionLayoutKind, testRecord>
fileprivate typealias DataSourceSnapshot = NSDiffableDataSourceSnapshot<SectionLayoutKind, testRecord>
override func viewDidLoad() {
super.viewDidLoad()
setRecordItems()
configureHierarchy()
configureDataSource()
applySnapshot()
}
func setRecordItems(){
for i in 0...3{
let record = testRecord(daysBack: i/2, progression: i/10)
records.append(record)
}
}
extension MediaViewController {
func configureHierarchy() {
collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: createLayout())
collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
collectionView.backgroundColor = .systemBackground
view.addSubview(collectionView)
collectionView.delegate = self
}
}
extension MediaViewController {
fileprivate enum SectionLayoutKind: Int, CaseIterable{
case records
case timeline
}
fileprivate func makeDataSource() -> DataSource {
let dataSource = DataSource(
collectionView: collectionView,
cellProvider: { (collectionView, indexPath, testRecord) ->
UICollectionViewCell? in
// 2
switch indexPath.section {
case 0:
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: RecordCollectionViewCell.identifier, for: indexPath) as? RecordCollectionViewCell
cell?.configure(with: testRecord)
return cell
case 1:
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: TimelineDayCell.identifier, for: indexPath) as? TimelineDayCell
cell?.configure(with: testRecord)
return cell
default:
return UICollectionViewCell()
}
})
return dataSource
}
func configureDataSource() {
collectionView.register(RecordCollectionViewCell.nib, forCellWithReuseIdentifier: RecordCollectionViewCell.identifier)
collectionView.register(TimelineDayCell.nib, forCellWithReuseIdentifier: TimelineDayCell.identifier)
}
func applySnapshot(animatingDifferences: Bool = true) {
// 2
var snapshot = DataSourceSnapshot()
SectionLayoutKind.allCases.forEach {
snapshot.appendSections([$0])
let records_copy = records
snapshot.appendItems(records_copy, toSection: $0)
}
dataSource.apply(snapshot, animatingDifferences: animatingDifferences)
}
}
所以设置是有两个部分,记录和时间线。它们都由相同的数据运行 - 记录数组。目前,当我每次应用快照时,我都在从类中复制这个数组——我不确定出于某种原因使用同一个数组是不好的..
然后在设置数据源时,对于 cellProvider,我有一个 switch 语句来检查该部分。如果它的第 0 部分我将使用一个记录单元,如果它的第 1 部分我将使用一个时间线单元。
目前没有生产记录单元。当我检查collectionView.numberOfItems(inSection:0)
它的 0.
collectionView.numberOfItems(inSection:1)
是 4 (记录的数量)
为什么两个部分都不是4?我怎样才能做到这一点?