UICollectionView长按移动位置

本文主要简单讲解一下美团标签长按移动交换位置并保存当前状态,下次开启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下载

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,460评论 25 708
  • 上学的时候,写作文最喜欢引用庄子的那句“人生天地之间,若白驹之过隙,忽然而已”真是少年不知愁滋味幼稚可爱。今天,日...
    雨停_阅读 137评论 0 0
  • 木子又一次等在柏来楼下时她哭着问:我到底哪里不够好?柏来冷冷的甩开她的手,不耐烦的说:你知不知道你很烦啊,能不能不...
    希希兮兮阅读 185评论 2 3
  • 我從小就希望有一位疼我的姐姐——直到30歲後才發現了這個需求。因為我是長房長孫,上面只有幾個表哥。我的母親呢,是非...
    丁子然阅读 329评论 0 1
  • 1、今天公司那边的人来搬木板,我看他们很累,就让我们的老师去帮忙,意想不到我们老师们很爽快的答应了,向荣老师和小陈...
    Wan9sha阅读 171评论 0 0