我在屏幕上有三部分数据:一个是五星项目,一个是访问,另一个是其他有趣的地方。它们都是相同类型的: funPlaces。对于本例,我将创建三个funPlaces数组,并在三个部分中显示它们。
如果没有可用的数据,我想要做的就是在屏幕上根本不生成一个区段。因此,如果没有访问数据,我只想看看五星项目和其他有趣的地方项目的章节。如果没有五星项目,我只想看看参观的部分和其他有趣的地方项目,等等。
然而..。
例如,如果没有访问项目,而不是如我所预期的那样访问部分消失了,相反,来自otherFunPlaces的数据将显示在屏幕上的访问部分,而整个其他有趣的地方部分消失了。是的,访问数据已经消失,但是这个部分仍然存在,它的数据已经被屏幕上其他有趣的地方数据所取代。
如果我有一个空的五星项目数组,则仍然会显示五星项目部分,但是数据已经被屏幕上的访问数据所取代。其他有趣的地方数据会转移到访问部分--实际上屏幕上消失的是另一个有趣的地方部分。
唯一可行的情况是,如果我有一个空的其他有趣项数组--该部分会如预期的那样消失,并且上面两个部分中的数据也在屏幕上的适当位置。
我错过了什么才能让这件事成功?
func applySnapshot(animatingDifferences: Bool = true) {
let funPlaces = fetchedResultsController.fetchedObjects ?? []
if funPlaces.count > 6 {
// we only generated enough sample data objects in viewDidLoad for this test
// we're going to make sure there are no fiveStarItems in the array for this test
// let fiveStarItems = Array<FunPlace>(funPlaces[0...1])
let fiveStarItems: [FunPlace] = [] // hide fiveStarItems
// we're going to keep data in visitsItems and otherItems
let visitsItems = Array<FunPlace>(funPlaces[2...3])
let otherFunPlacesItems = Array<FunPlace>(funPlaces[4...5])
var snapshot = NSDiffableDataSourceSnapshot<Sections, FunPlace>()
if !fiveStarItems.isEmpty {
snapshot.appendSections([Sections.fiveStar])
snapshot.appendItems(fiveStarItems, toSection: .fiveStar)
}
if !visitsItems.isEmpty {
snapshot.appendSections([Sections.visits])
snapshot.appendItems(visitsItems, toSection: .visits)
}
if !otherFunPlacesItems.isEmpty {
snapshot.appendSections([Sections.otherFunPlaces])
snapshot.appendItems(otherFunPlacesItems, toSection: .otherFunPlaces)
}
dataSource?.apply(snapshot, animatingDifferences: true)
}
}谢谢。
发布于 2022-08-26 11:53:35
在创建布局时,请确保根据节标识符(而不是节号)执行布局。这样,没有数据的任何部分都不会显示:
let layout = UICollectionViewCompositionalLayout(sectionProvider: { sectionNumber, env in
let sectionIdentifier = self.dataSource.snapshot().sectionIdentifiers[sectionNumber]
if sectionIdentifier == .fiveStar {
return FiveStarSectionLayout....
} else if (sectionIdentifier == .visits) {
return VisitsSectionLayout....
} else if sectionIdentifier == .otherFunPlaces) {
return OtherFunPlacesSectionLayout...
} else {
return nil
}
})
self.collectionView.setCollectionViewLayout(layout, animated: true)发布于 2022-04-21 18:39:09
我想通了。
问题是编制要列出的章节的索引。我必须单独跟踪可用的部分,并且只列出可用的部分。
https://stackoverflow.com/questions/71949717
复制相似问题