美文网首页
UICollectionView长按移动位置

UICollectionView长按移动位置

作者: 木马不在转 | 来源:发表于2017-04-27 21:02 被阅读117次

本文主要简单讲解一下美团标签长按移动交换位置并保存当前状态,下次开启APP顺序不变的功能。

1:核心API

//开始移动
- (BOOL)beginInteractiveMovementForItemAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(9_0);
//实时更新cell的point
- (void)updateInteractiveMovementTargetPosition:(CGPoint)targetPosition NS_AVAILABLE_IOS(9_0);
//结束移动并插入到相应位置
- (void)endInteractiveMovement NS_AVAILABLE_IOS(9_0);
//取消插入
- (void)cancelInteractiveMovement NS_AVAILABLE_IOS(9_0);

2:主要方法

//长按手势触发方法
- (void)lonePressMoving:(UILongPressGestureRecognizer *)longPress
{
switch (self.longPress.state) {
    // 开始操作
    case UIGestureRecognizerStateBegan: {
        {
            NSIndexPath *selectIndexPath = [self.collectionView indexPathForItemAtPoint:[_longPress locationInView:self.collectionView]];
           // 判断手势落点位置是否在路径上
            if (selectIndexPath == nil) { break; }
            
            // 找到当前的cell
            self.pressCell = (ZKCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:selectIndexPath];
            [self starLongPress:self.pressCell];
            [self.collectionView beginInteractiveMovementForItemAtIndexPath:selectIndexPath];
        }
        break;
    }
  // 移动中
    case UIGestureRecognizerStateChanged: {
        [self.collectionView updateInteractiveMovementTargetPosition:[longPress locationInView:_longPress.view]];
        break;
    }
  // 结束操作
    case UIGestureRecognizerStateEnded: {
        [self.collectionView endInteractiveMovement];
        [self endAnimation];
        break;
    }
 // 其它操作
    default: [self.collectionView cancelInteractiveMovement];
        [self endAnimation];
        break;
  }
}
//移动结束后代理
- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(nonnull NSIndexPath *)sourceIndexPath toIndexPath:(nonnull NSIndexPath *)destinationIndexPath
{
/***2中排序方式,第一种只是交换2个cell位置,第二种是将前面的cell都往后移动一格,再将cell插入指定位置***/
 // first
//    [self.dataArray exchangeObjectAtIndex:sourceIndexPath.item withObjectAtIndex:destinationIndexPath.item];

// second
id objc = [self.dataArray objectAtIndex:sourceIndexPath.item];
//从资源数组中移除该数据
[self.dataArray removeObject:objc];
//将数据插入到资源数组中的目标位置上
[self.dataArray insertObject:objc atIndex:destinationIndexPath.item];

/**保存数据顺序**/
[ZKTool cacheUserValue:self.dataArray.copy key:cellOrder_key];
[self.collectionView reloadData];
}

3:效果展示

效果GIF
github下载

相关文章

网友评论

      本文标题:UICollectionView长按移动位置

      本文链接:https://www.haomeiwen.com/subject/vapnzttx.html