Reputation: 42710
I use the following code snippet to implement drag and reorder operation.
class DashboardViewController {
private func initCollectionView() {
...
let gesture = UILongPressGestureRecognizer(target: self, action: #selector(longPressGesture))
collectionView.addGestureRecognizer(gesture)
}
@objc func longPressGesture(_ gesture: UILongPressGestureRecognizer) {
switch gesture.state {
case .began:
self.began(gesture)
case .changed:
self.changed(gesture)
case .ended:
self.ended(gesture)
default:
self.cancel(gesture)
}
}
}
extension DashboardViewController {
func began(_ gesture: UILongPressGestureRecognizer) {
print(">> began")
let location = gesture.location(in: self.collectionView)
guard let indexPath = self.collectionView.indexPathForItem(at: location) else {
return
}
collectionView.beginInteractiveMovementForItem(at: indexPath)
}
func changed(_ gesture: UILongPressGestureRecognizer) {
print(">> changed")
collectionView.updateInteractiveMovementTargetPosition(location)
}
func ended(_ gesture: UILongPressGestureRecognizer) {
print(">> ended")
collectionView.endInteractiveMovement()
}
func cancel(_ gesture: UILongPressGestureRecognizer) {
print(">> cancel")
collectionView.endInteractiveMovement()
}
}
As you can see in the screenshot, when I start to drag and 1st cell, changed
will keep being called.
When I drag close enough to the 2nd cell, the 2nd cell will then visually switch position to 1st.
I would like to be able to detect, when the 2nd cell is visually switch position to the 1st. Does anyone know how I can achieve so?
Thanks.
Upvotes: 3
Views: 386
Reputation: 16446
You may not able to find the visually cell is switched to the 1st position but you may try to check after some delay when switching is happening
you will get this delegate method called when you drag the cell
optional func collectionView(_ collectionView: UICollectionView,
targetIndexPathForMoveOfItemFromOriginalIndexPath originalIndexPath: IndexPath,
atCurrentIndexPath currentIndexPath: IndexPath,
toProposedIndexPath proposedIndexPath: IndexPath) -> IndexPath
here is the doc url
https://developer.apple.com/documentation/uikit/uicollectionviewdelegate/3750828-collectionview
Upvotes: 2