努力了解如何为moveItemAt-UICollectionViewCell实现IGListDiff?

时间:2019-04-25 09:49:15

标签: ios swift uicollectionview iglistkit

我正在使用IGListKitIGListDiff部分  开源框架。

它使我可以更轻松地在应用程序中的UICollectionViewUICollectionViewCell上进行操作,操作和更新。

但是我正在努力了解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的人的任何帮助,将不胜感激。

0 个答案:

没有答案