首先给collectionview添加长按方法
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handlelongGesture:)];
[self.issueCollectionView addGestureRecognizer:longPress];
#pragma mark 长按响应方法
- (void)handlelongGesture:(UILongPressGestureRecognizer *)longPress {
[self action:longPress];
}
- (void)action:(UILongPressGestureRecognizer *)longPress {
switch (longPress.state) {
case UIGestureRecognizerStateBegan:
{
//手势开始
//判断手势落点位置是否在row上
NSIndexPath *indexPath = [self.issueCollectionView indexPathForItemAtPoint:[longPress locationInView:self.issueCollectionView]];
if (indexPath == nil || indexPath.row >= self.arrayList.count) {
break;
}
IssueCollectionViewCell *cell = (IssueCollectionViewCell *)[self.issueCollectionView cellForItemAtIndexPath:indexPath];
[self.issueCollectionView bringSubviewToFront:cell];
//iOS9 方法 移动cell
[self.issueCollectionView beginInteractiveMovementForItemAtIndexPath:indexPath];
}
break;
case UIGestureRecognizerStateChanged:
{
//iOS9 方法 移动过程中随时更新cell位置
[self.issueCollectionView updateInteractiveMovementTargetPosition:[longPress locationInView:self.issueCollectionView]];
}
break;
case UIGestureRecognizerStateEnded:
{
//手势结束
//iOS9方法 移动结束后关闭cell移动
[self.issueCollectionView endInteractiveMovement];
}
break;
default:
[self.issueCollectionView cancelInteractiveMovement];
break;
}
}
之后对拖拽后的数据位置进行排序
//开启collectionView可以移动
- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath {
return YES;
}
//处理collectionView移动过程中的数据操作
- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
//取出移动row 数据
FXEComObject *childCom = self.arrayList[sourceIndexPath.row];
//从数据源中移除该数据
[self.arrayList removeObject:childCom];
if (destinationIndexPath.row >= self.arrayList.count) {
[self.arrayList insertObject:childCom atIndex:destinationIndexPath.row - 1];
} else {
//将数据插入到数据源中目标位置
[self.arrayList insertObject:childCom atIndex:destinationIndexPath.row];
}
[UIView performWithoutAnimation:^{
[self.issueCollectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
}];
}