UICollectionview进阶:自定义布局(-) - 掘金
拖拽动画步骤
- 添加长按手势
- 对手势状态监听
- 拖拽之后对数据源的改变
添加长按手势
self.longPress = UILongPressGestureRecognizer.init(target: self, action: #selector(longPressMoving(longPress:)))
self.collectionView?.addGestureRecognizer(self.longPress!)
复制代码
对手势状态监听
@objc func longPressMoving(longPress: UILongPressGestureRecognizer) {
switch longPress.state {
case .began:
//这里是上报的当前Cell的IndexPath
//手势作用的位置
let point = longPress.location(in: self.collectionView)
let selectIndexPath = self.collectionView?.indexPathForItem(at: point)
//找到当前的cell
let selectCell = self.collectionView?.cellForItem(at: selectIndexPath!)
//拽起变大动画效果
UIView.animate(withDuration: 0.2) {
selectCell?.transform = CGAffineTransform(scaleX: 1.1, y: 1.1)
}
//开始移动
self.collectionView?.beginInteractiveMovementForItem(at: selectIndexPath!)
case .changed:
//这里上报的是当前触摸点的位置
let point = longPress.location(in: self.collectionView)
//更新移动的位置
self.collectionView?.updateInteractiveMovementTargetPosition(point)
case .ended:
//结束移动
self.collectionView?.endInteractiveMovement()
default:
//移动失败或者取消
//选中状态清除
self.collectionView?.cancelInteractiveMovement()
}
}
复制代码
- began://开始移动
- changed://位置发生变化,更新移动的位置
- ended: //结束移动
- default: //移动失败或者取消,需要清除状态
获取当前的触摸点
let point = longPress.location(in: self.collectionView)
拖拽之后对数据源的改变
// MARK: 拖动
func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool {
return true
}
func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
print("sourceIndexPath.row=\(sourceIndexPath.row);;;destinationIndexPath.row=\(destinationIndexPath.row);;;")
let sourceNumber = self.dataArray[sourceIndexPath.row]
self.dataArray.remove(at: sourceIndexPath.row)
self.dataArray.insert(sourceNumber, at: destinationIndexPath.row)
}
复制代码
把起始位置的数据和终点位置的数据进行交换。