ios CollectionView 的手势拖动cell交换

今日头条中的项目编辑有个拖动item交换位置的功能,在iOS 9 中collectionView也公开了一套方法用来实现该功能,也是方便到不行.这里做一个记载.

 - (BOOL)beginInteractiveMovementForItemAtIndexPath:(NSIndexPath *)indexPath;
 - (void)updateInteractiveMovementTargetPosition:(CGPoint)targetPosition ;
 - (void)endInteractiveMovement;
- (void)cancelInteractiveMovement;

以上api都是在iOS9才可以使用,然而也有些点要注意.

  1. 代理方法中的

    - (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath;
    - (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath*)destinationIndexPath ;
    

这两个方法一定要实现.第一个方法可以设定特定的cell不让其移动.而第二个方法则是用来完成移动后对数据源进行处理,毕竟我们刚才的交换只是完成了动画部分.

核心代码为:

- (void)_longPressAction:(UILongPressGestureRecognizer *)sender{
      UIGestureRecognizerState status = sender.state;
      CGPoint p = [sender locationInView:_imageCollectionView];
      NSIndexPath *indexPath = [_imageCollectionView indexPathForItemAtPoint:p];
      if(!indexPath)return;
     //获取cell用来做动画
      UICollectionViewCell *cell = [_imageCollectionView cellForItemAtIndexPath:indexPath];

      switch (status) {
          case UIGestureRecognizerStateBegan:
        {
            NSLog(@"%d",[_imageCollectionView beginInteractiveMovementForItemAtIndexPath:indexPath]);
            [UIView animateWithDuration:0.2 animations:^{
                cell.transform = CGAffineTransformScale(cell.transform, 0.8, 0.8);
            }];
        }
        break;
    case UIGestureRecognizerStateChanged:
    {
        [_imageCollectionView updateInteractiveMovementTargetPosition:p];
    }
        break;
        
    default:
        {
            [_imageCollectionView endInteractiveMovement];
            [UIView animateWithDuration:0.2 animations:^{
                cell.transform = CGAffineTransformIdentity;
            }];
        };
}}

你可能感兴趣的:(ios CollectionView 的手势拖动cell交换)