1.添加长按手势
UILongPressGestureRecognizer *longPresssGes = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressMethod:)];
[self.myCollectionView addGestureRecognizer:longPresssGes];
2.处理手势关联
- (void)longPressMethod:(UILongPressGestureRecognizer *)longPressGes {
// 判断手势状态
switch (longPressGes.state) {
case UIGestureRecognizerStateBegan: {
// 判断手势落点位置是否在路径上(长按cell时,显示对应cell的位置,如path = 1 - 0,即表示长按的是第1组第0个cell). 点击除了cell的其他地方皆显示为null
NSIndexPath *indexPath = [self.myCollectionView indexPathForItemAtPoint:[longPressGes locationInView:self.myCollectionView]];
// 如果点击的位置不是cell,break
if (nil == indexPath) {
break;
}
NSLog(@"%@",indexPath);
// 在路径上则开始移动该路径上的cell
[self.myCollectionView beginInteractiveMovementForItemAtIndexPath:indexPath];
}
break;
case UIGestureRecognizerStateChanged:
// 移动过程当中随时更新cell位置
[self.myCollectionView updateInteractiveMovementTargetPosition:[longPressGes locationInView:self.myCollectionView]];
break;
case UIGestureRecognizerStateEnded:
// 移动结束后关闭cell移动
[self.myCollectionView endInteractiveMovement];
break;
default:
[self.myCollectionView cancelInteractiveMovement];
break;
}
}
3.数据源处理
- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
NSDictionary *dic = self.myHobbiesArray[sourceIndexPath.row];
[self.myHobbiesArray removeObject:dic];
[self.myHobbiesArray insertObject:dic atIndex:destinationIndexPath.row];
}