我的应用程序提供了一个表情符号键盘,就像苹果按类别显示表情符号的地方。我使用集合视图呈现这一点,其中类别是节。如果最近插入了一个表情符号,它应该出现在“经常使用的”类别中,以及它通常属于的任何类别中。
这对我试图将集合视图转换为使用UICollectionViewDiffableDataSource是一个问题,因为NSDiffableDataSourceSnapshot要求项是唯一的。如果我做了这样的事
let snapshot = NSDiffableDataSourceSnapshot<Section, Emoji>()
snapshot.appendItems([thumbsUpEmoji], toSection: .frequents)
snapshot.appendItems([thumbsUpEmoji], toSection: .smileys)
dataSource.apply(snapshot)我收到警告就像
插入标识符已经存在;现有项将被移动到当前插入的位置。如果插入的项目不是唯一的,请注意这将影响性能。
表情符号只出现在一个区域,而不是两者都出现。如何将项目插入多个区段?
发布于 2020-06-15 21:46:15
我发现,我能够通过将表情符号包装在与其节关联的结构中来做到这一点:
struct CategorizedEmoji: Hashable {
let emoji: Emoji
let category: Section
}然后,我的数据源是UICollectionViewDiffableDataSource<Section, CategorizedEmoji>类型和NSDiffableDataSourceSnapshot<Section, CategorizedEmoji>类型的快照。在构造快照时,我会这样做
let snapshot = NSDiffableDataSourceSnapshot<Section, CategorizedEmoji>()
snapshot.appendItems([CategorizedEmoji(emoji: thumbsUpEmoji, category: .frequents)], toSection: .frequents)
snapshot.appendItems([CategorizedEmoji(emoji: thumbsUpEmoji, category: .smileys)], toSection: .smileys)
dataSource.apply(snapshot)有点冗长,但也不算太糟。
注意:我想这个解决方案将阻止表情符号在各部分之间移动(因为不同部分中的表情符号将由一个完全不同的项表示)。我个人不需要处理这件事,但我希望看到一个确实解决了这个问题的答案。
发布于 2022-05-13 22:51:56
下面是一个通用实现,因此您可以将其用于所有分段列表:
/// The following allows items to be used across different shard key-spaces, by combining a shard's hash values with the item's hash.
///
/// EXAMPLE: For sectioned UICollectionViews, simply use a section identifier as the sharding key to allow items to show up in multiple sections-
struct ShardedItem<TShardingKey, TItem> : Hashable
where TShardingKey:Hashable, TItem:Hashable
{
let shard:TShardingKey
let item:TItem
}然后简单地像这样使用它:
注意:使用iOS 14 https://levelup.gitconnected.com/building-an-expandable-list-using-uicollectionview-part-1-703312c2d773
var snapshot = NSDiffableDataSourceSnapshot<Section, ShardedItem<Section, Thing>>()
snapshot.appendSections( [.topThings, .allThings] )
self.dataSource.apply( snapshot, animatingDifferences: false )
let allThings:[Thing] = ...
let topThings:[Thing] = allThings.filter{ $0.isFeatured }
var topThingsSectionSnapshot = NSDiffableDataSourceSectionSnapshot<ShardedItem<Section, Thing>>()
topThingsSectionSnapshot.append( topThings.map { ShardedItem( shard: .topThings, item: $0 )})
self.dataSource.apply( topThingsSectionSnapshot, to: .topThings )
var allThingsSectionSnapshot = NSDiffableDataSourceSectionSnapshot<ShardedItem<MinorRegionsSection, MinorRegionListItem>>()
allThingsSectionSnapshot.append( allThings.map { ShardedItem( shard: .allThings, item: $0 )})
self.dataSource.apply( allThingsSectionSnapshot, to: .allThings )https://stackoverflow.com/questions/62397539
复制相似问题