在 drag-n-reorder 操作期间,如何检测单元格何时在视觉上被切换位置?

During drag-n-reorder operation, how to detect when the cell is visually being switched position?

我使用以下代码片段来实现拖动和重新排序操作。

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()
    }
}

正如您在屏幕截图中看到的,当我开始拖动第一个单元格时,changed 将继续被调用。

当我拖动到足够靠近第二个单元格时,第二个单元格将在视觉上切换到第一个单元格的位置。

我希望能够检测到,当第二个单元格在视觉上切换到第一个单元格时。有谁知道我怎样才能做到这一点?

谢谢。

您可能无法发现视觉单元格已切换到第一个位置,但您可以在切换发生时延迟一段时间后尝试检查

您将在拖动单元格时调用此委托方法

optional func collectionView(_ collectionView: UICollectionView, 
       targetIndexPathForMoveOfItemFromOriginalIndexPath originalIndexPath: IndexPath, 
      atCurrentIndexPath currentIndexPath: IndexPath, 
     toProposedIndexPath proposedIndexPath: IndexPath) -> IndexPath

这是文档url

https://developer.apple.com/documentation/uikit/uicollectionviewdelegate/3750828-collectionview