Handle moveItem(at:to:) delegate method when using UICollectionViewDiffableDataSource

Viewed 365

I need to use moveItem(at:to:) delegate method in order to move my collection view cells. When I implement the data source delegation methods it's working fine, but I need to set my data source as UICollectionViewDiffableDataSource and in this way the moveItem(at:to:) did not call. Any solution to handle,

This way it's work when using delegations :


override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
       return 10
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CustomCell
        cell.textLabel.text = "Some value"
        return cell
}

override func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool {
        true
}

override func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        print("OK")
}

set data source in this way is not work


func setupDataSource() {
        dataSource = UICollectionViewDiffableDataSource<Section, Person>(collectionView: collectionView, cellProvider: {
            (collectionView: UICollectionView, indexPath: IndexPath, person: Person) -> UICollectionViewCell? in
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CustomCell
            cell.textLabel.text = "Some text"
            return cell
        })
    }
1 Answers

For custom behavior create a subclass of UICollectionViewDiffableDataSource and override the methods there.

Related