UICollectionView实现cell拖动效果
1.在UICollectionView的视图上添加长按手势
UILongPressGestureRecognizer *longGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handlelongGesture:)];
[self.collectionView addGestureRecognizer:longGesture];
2.在点击的时候,获取到当前点击的cell的indexpath,并在不同的手势状态下,进行一些判断或者添加一些约束条件【因为我的情景是cell中显示不同的服务,而最后一个cell与其他不同,不参与排序,所以我需要保证拖动的cell不可以到最后一个位置,并且最后一个cell不可以拖动】
- (void)handlelongGesture:(UILongPressGestureRecognizer *)longGesture {
NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:[longGesture locationInView:self.collectionView]];
UICollectionViewCell *tmpCell = [self.collectionView cellForItemAtIndexPath:indexPath];
[tmpCell.layer shake];
//判断手势状态
switch (longGesture.state) {
case UIGestureRecognizerStateBegan:{
[tmpCell.layer playSystemShake];
//判断手势落点位置是否在路径上
if (indexPath == nil) {
break;
}
//在路径上则开始移动该路径上的cell
[self.collectionView beginInteractiveMovementForItemAtIndexPath:indexPath];
}
break;
case UIGestureRecognizerStateChanged:
NSLog(@"%lu",(unsigned long)_showDataArr.count);
//判断是否落在最后的加号上
if (indexPath.row == _showDataArr.count) {
break;
}
//移动过程当中随时更新cell位置
[self.collectionView updateInteractiveMovementTargetPosition:[longGesture locationInView:self.collectionView]];
break;
case UIGestureRecognizerStateEnded:
//移动结束后关闭cell移动
[self.collectionView endInteractiveMovement];
break;
default:
[self.collectionView cancelInteractiveMovement];
break;
}
}
3我们还需要实现UIcollectionView的一个代理方法,并保证不参与拖动的cell不可移动
- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath{
//返回YES允许其item移动
if(indexPath.row != [_showDataArr count]) {
return YES;
}
return NO;
}
4实现数据的重新排序
- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath*)destinationIndexPath {
//取出源item数据
id objc = [_showDataArr objectAtIndex:sourceIndexPath.item];
//从资源数组中移除该数据
[_showDataArr removeObject:objc];
//将数据插入到资源数组中的目标位置上
[_showDataArr insertObject:objc atIndex:destinationIndexPath.item];
NTSubscribeModel *model = [NTSubscribeModel new];
[model updateServicesOrder:_showDataArr];
model = nil;
}