swift 拖动collectionCell并改变其位置和数据位置

老规矩 先上图:
QQ20181010-151146-HD.gif

1.为cell添加长按手势

let tap = UILongPressGestureRecognizer(target: self, action: #selector(delectBtn(_:)))
tap.minimumPressDuration = 1
tap.numberOfTouchesRequired = 1
cell.addGestureRecognizer(tap)

2.为长按手势添加事件

@objc func delectBtn(_ sender: UILongPressGestureRecognizer) {
    switch sender.state {
    case .began:
       //取得要移动cell的索引
       let selectedCellIndex = collectionView.indexPathForItem(at: sender.location(in: collectionView))
        //开始移动
            collectionView.beginInteractiveMovementForItem(at: selectedCellIndex!)
    case .changed:
        //移动ing
        collectionView.updateInteractiveMovementTargetPosition(sender.location(in: collectionView))
    case .ended:
        //结束移动
        collectionView.endInteractiveMovement()
    default:
        //取消移动
        collectionView.cancelInteractiveMovement()
    }
    
}

3.处理移动后数据的改变

//sourceIndexPath.item移动前cell的索引
//destinationIndexPath.item移动后的索引
func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
    let tempMybook = mybook[sourceIndexPath.item]
    mybook.remove(at: sourceIndexPath.item)
    mybook.insert(tempMybook, at: destinationIndexPath.item)
}

你可能感兴趣的:(swift 拖动collectionCell并改变其位置和数据位置)