我有一个 UICollectionViewDiffableDataSource 用于垂直滚动,具有动态高度单元格。
每次我在数据源上调用“应用”时,集合视图都会滚动一点,看起来不太好。如何防止它滚动?
private func applySnapshot(completion: @escaping () -> ()) {
let sections = presenter.getSections().filter({$0.date != nil} ).map({$0.date!})
var snapshot = Snapshot()
snapshot.appendSections(sections)
sections.forEach { (date) in
if var events = presenter.getEvents(by: date) {
if events.isEmpty {
events = [Event(emptyEventDate: date)]
}
snapshot.appendItems(events, toSection: date)
}
}
self.dataSource.apply(snapshot, animatingDifferences: false) {
completion()
}
}
private func createLayout() -> UICollectionViewLayout {
let kHeaderHeight: CGFloat = 25
let kSectionInsetTop: CGFloat = 8
let kSectionInsetLeadingTrailing: CGFloat = 15
let kSectionInsetBottom: CGFloat = 28
let kItemSpacing: CGFloat = 12
let estimatedHeight = CGFloat(400)
let layoutSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0),
heightDimension: .estimated(estimatedHeight))
let item = NSCollectionLayoutItem(layoutSize: layoutSize)
let group = NSCollectionLayoutGroup.horizontal(layoutSize: layoutSize,
subitem: item,
count: 1)
group.contentInsets = NSDirectionalEdgeInsets(
top: 0,
leading: kSectionInsetLeadingTrailing,
bottom: 0,
trailing: kSectionInsetLeadingTrailing)
let section = NSCollectionLayoutSection(group: group)
section.contentInsets = NSDirectionalEdgeInsets(
top: kSectionInsetTop,
leading: 0,
bottom: kSectionInsetBottom,
trailing: 0)
section.interGroupSpacing = kItemSpacing
let headerSize = NSCollectionLayoutSize(
widthDimension: .fractionalWidth(1.0),
heightDimension: .absolute(kHeaderHeight)
)
let sectionHeader = NSCollectionLayoutBoundarySupplementaryItem(
layoutSize: headerSize,
elementKind: UICollectionView.elementKindSectionHeader,
alignment: .top
)
sectionHeader.pinToVisibleBounds = true
section.boundarySupplementaryItems = [sectionHeader]
let layout = UICollectionViewCompositionalLayout(section: section)
return layout
}
我感谢您的帮助
- 编辑:当我在可见单元格之前插入新项目/部分时,我看到视图“跳跃”/滚动了一下。如果我在它不会发生之后插入。