在视图中,苹果展示了一个关于如何使用DiffableDataSource执行重新排序的简单示例
ReorderableListViewController.swift
dataSource.reorderingHandlers.canReorderItem = { item in return true }
dataSource.reorderingHandlers.didReorder = { [weak self] transaction in
guard let self = self else { return }
// method 1: enumerate through the section transactions and update
// each section's backing store via the Swift stdlib CollectionDifference API
if self.reorderingMethod == .collectionDifference {
for sectionTransaction in transaction.sectionTransactions {
let sectionIdentifier = sectionTransaction.sectionIdentifier
if let previousSectionItems = self.backingStore[sectionIdentifier],
let updatedSectionItems = previousSectionItems.applying(sectionTransaction.difference) {
self.backingStore[sectionIdentifier] = updatedSectionItems
}
}
// method 2: use the section transaction's finalSnapshot items as the new updated ordering
} else if self.reorderingMethod == .finalSnapshot {
for sectionTransaction in transaction.sectionTransactions {
let sectionIdentifier = sectionTransaction.sectionIdentifier
self.backingStore[sectionIdentifier] = sectionTransaction.finalSnapshot.items
}
}
}有什么办法,限制重新排序只能在同一节内执行吗?
在reorderingHandlers.canReorderItem中我们所能做的不多,因为闭包参数item引用的是我们正在拖动的当前源项。没有关于目标项的信息,我们可以与其进行比较,以决定是否返回true或false。
发布于 2021-04-04 20:44:11
对于数据源来说,这种行为不是一个问题。这是你的代表的问题
可以使用:targetIndexPathForMoveFromItemAt:toProposedIndexPath:)来确定是否允许移动。
func collectionView(_ collectionView: UICollectionView,
targetIndexPathForMoveFromItemAt originalIndexPath: IndexPath,
toProposedIndexPath proposedIndexPath: IndexPath) -> IndexPath {
let sourceSection = sourceIndexPath.section
let destSection = proposedDestinationIndexPath.section
var destination = proposedDestinationIndexPath
if destSection < sourceSection {
destination = IndexPath(item: 0, section: sourceSection)
} else if destSection > sourceSection {
destination = IndexPath(item: self.backingStore[sourceSection].count-1, section: sourceSection)
}
return destination
}这限制了项目的移动到它自己的部分。
发布于 2021-10-13 00:28:35
如果您的项目有标题,这里有一种不同的方法:
dataSource.reorderingHandlers.canReorderItem = {item in
let exclude = ["Library","Favorites","Recents","Search","All"]
if(exclude.contains(item.title!)){return false}
return true
}发布于 2021-05-07 17:16:37
您也可以在委托方法collectionView(_:targetIndexPathForMoveFromItemAt:toProposedIndexPath:)中使用这种记录。
func collectionView(_ collectionView: UICollectionView, targetIndexPathForMoveFromItemAt originalIndexPath: IndexPath, toProposedIndexPath proposedIndexPath: IndexPath) -> IndexPath {
if originalIndexPath.section != proposedIndexPath.section {
return originalIndexPath
}
return proposedIndexPath
}我在Matt关于编程iOS 14的书中读到了这篇文章,它工作得很好:)
https://stackoverflow.com/questions/66940887
复制相似问题