我正在使用IGListKit的IGListDiff
部分
开源框架。
它使我可以更轻松地在应用程序中的UICollectionView
和UICollectionViewCell
上进行操作,操作和更新。
但是我正在努力了解moveItemAt
的实现。
实际上,我希望能够将我的UICollectionViewCell
从长按中移开。看来IGListDiff
可以处理它(移动是插入和删除)。
这是我对moveItemAt
的实现:
func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
let item = items.remove(at: sourceIndexPath.item)
items.insert(item, at: destinationIndexPath.item)
}
没什么特别的,没有它我就无法移动我的细胞。但是它也触发了IGListDiff
的更新,因为我正在修改数据源,并且感觉像它“翻倍”了我的UICollectionView
的更新。
我正在 moveItemAt 中执行remove
/ insert
,但是在修改dataSource时也在我的perform方法中执行
extension UICollectionView {
func perform(result: DiffList.Result) {
if result.hasChanges {
self.performBatchUpdates({
if !result.deletes.isEmpty {
self.deleteItems(at: result.deletes.compactMap { IndexPath(row: $0, section: 0) })
}
if !result.inserts.isEmpty {
self.insertItems(at: result.inserts.compactMap { IndexPath(row: $0, section: 0) })
}
if !result.updates.isEmpty {
self.reloadItems(at: result.updates.compactMap { IndexPath(row: $0, section: 0) })
}
if !result.moves.isEmpty {
result.moves.forEach({ (index) in
let toIndexPath = IndexPath(row: index.to, section: 0)
self.moveItem(at: IndexPath(row: index.from, section: 0), to: toIndexPath)
})
}
})
}
}
}
最后,这是我的dataSource,它触发perform
方法进行任何修改:
private(set) var items = [AnyEquatableCellConfigurator]() {
didSet {
if oldValue.isEmpty {
self.collectionView.collectionViewLayout.invalidateLayout()
self.collectionView.reloadData()
} else {
let oldHashes = oldValue.map { $0.hash }
let newHashes = items.map { $0.hash }
let result = DiffList.diffing(oldArray: oldHashes, newArray: newHashes)
self.collectionView.perform(result: result)
}
}
}
对于已经使用moveItemAt
算法实现了DiffList
的人的任何帮助,将不胜感激。