UITableViewCell拖拽移动两种实现方法

作者: yuandiLiao | 来源:发表于2017-06-01 11:51 被阅读106次

1.UITableView协议方法的实现

使用协议方法相对比较简单。
将tableview设置为可编辑状态,然后实现协议方法中交换数据源和交换cell的位置即可。但是这种实现方法不够自定义,就是比较限制。

  • 可编辑状态的时候不能点击
  • 可编辑状态是右边会有几条杠。(如图)
  • 长按移动只有按住右边几条杠才能移动。
        _tableView.editing = YES;
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
    //移动cell前交换数据源
    [self.dataArray exchangeObjectAtIndex:sourceIndexPath.row withObjectAtIndex:destinationIndexPath.row];
    [self.tableView moveRowAtIndexPath:sourceIndexPath toIndexPath:destinationIndexPath];
}
协议方法实现.gif

2.自定义的实现

先上demo地址
使用可以将demo中的UITableView+MoveCell类别引入工程中,然后绑定数据源即可有拖拽效果啦。

  __weak typeof(self) weakSelf = self;
        [_tableView setDataWithArray:self.dataArray withBlock:^(NSMutableArray *newArray) {
            weakSelf.dataArray = newArray;
        }];

支持单section的tableview的拖动和多section数据源嵌套型数组的使用,也支持自动上下滑动。先看看效果吧。

单section.gif 多section嵌套数组.gif
实现思路

有点类似我上一篇写的UICollectionView实现长按cell抖动和拖拽移动(支持iOS9以下)
这里我是使用了给tableview添加了一个类别,在类别中实现拖拽效果,这样就能复用了,而且使用起来方便很多。只需要绑定数据源即可

1.首先给tableview添加一个长按手势
//绑定数据源和添加手势
-(void)setDataWithArray:(NSMutableArray *)array withBlock:(moveCellBlock)block{
    self.dataArray = [[NSMutableArray alloc] init];
    [self.dataArray addObjectsFromArray:array];
    self.block = block;
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
    [self addGestureRecognizer:longPress];
}
2.监测手势的响应方法中的状态响应,根据不同的状态响应不同操作,这里主要分为三个步骤
  • 手势开始时,将长按的cell进行截图,获取到的snapView加在tableview上面,然后将cell隐藏起来,这时候我们看到的就是snapView,拖动的也是snapView。
  • 手势改变即开始拖动时,这时候做的就是获取移动的位置,然后snapView跟着移动到改位置,这时候snapView可能会移动到上边缘和下边缘的位置,加上判断,如果移动上边缘和下边缘那么就让tableview自动上下滑动,接着更新数据源和交换cell的位置。
  • 手势结束即放手时,将snapview移除,原来的cell显示出来即可
-(void)longPress:(UILongPressGestureRecognizer *)longPress
{
    switch (longPress.state) {
        case UIGestureRecognizerStateBegan:{
            [self reloadData];
            CGPoint point = [longPress locationOfTouch:0 inView:longPress.view];
            self.indexPath = [self indexPathForRowAtPoint:point];
            //indexpath可能为空
            if (self.indexPath) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.moveCell = [self cellForRowAtIndexPath:self.indexPath];
                    self.snapView = [self.moveCell snapshotViewAfterScreenUpdates:NO];
                    self.snapView.frame = self.moveCell.frame;
                    [self addSubview:self.snapView];
                    self.moveCell.hidden = YES;
                    [UIView animateWithDuration:0.1 animations:^{
                        self.snapView.transform = CGAffineTransformScale(self.snapView.transform, 1.03, 1.05);
                        self.snapView.alpha = 0.8;
                    }];
                });
            }
        }
            break;
        case UIGestureRecognizerStateChanged:{
            CGPoint point = [longPress locationOfTouch:0 inView:longPress.view];
            CGPoint center  = self.snapView.center;
            center.y = point.y;
            self.snapView.center = center;
            if ([self checkIfSnapshotMeetsEdge]) {
                [self startAutoScrollTimer];
            }else{
                [self stopAutoScrollTimer];
            }
            NSIndexPath *exchangeIndex = [self indexPathForRowAtPoint:point];
            //exchangeIndex可能为空
            if (exchangeIndex) {
                [self updateDataWithIndexPath:exchangeIndex];
                [self moveRowAtIndexPath:self.indexPath toIndexPath:exchangeIndex];
                self.indexPath = exchangeIndex;
            }
        }
            break;
        case UIGestureRecognizerStateEnded:{
            dispatch_async(dispatch_get_main_queue(), ^{
                self.moveCell  = [self cellForRowAtIndexPath:self.indexPath];
                [UIView animateWithDuration:0.2 animations:^{
                    self.snapView.center = self.moveCell.center;
                    self.snapView.transform = CGAffineTransformIdentity;
                    self.snapView.alpha = 1.0;
                } completion:^(BOOL finished) {
                    self.moveCell.hidden = NO;
                    [self.snapView removeFromSuperview];
                    [self stopAutoScrollTimer];
                }];
            });
        }
            break;
        default:
            break;
    }
}

更新数据源

-(void)updateDataWithIndexPath:(NSIndexPath *)moveIndexPath
{
    //判断是否是嵌套数组
    if ([self nestedArrayCheck:self.dataArray]) {
        if (self.indexPath.section == moveIndexPath.section) {
            NSMutableArray *originalArray = self.dataArray[self.indexPath.section];
            [originalArray exchangeObjectAtIndex:self.indexPath.row withObjectAtIndex:moveIndexPath.row];
        }else{
            NSMutableArray *originalArray = self.dataArray[self.indexPath.section];
            NSMutableArray *removeArray = self.dataArray[moveIndexPath.section];
            NSString * obj = [originalArray objectAtIndex:self.indexPath.row];
            [removeArray insertObject:obj atIndex:moveIndexPath.row];
            [originalArray removeObjectAtIndex:self.indexPath.row];
        }
    }else{
        [self.dataArray exchangeObjectAtIndex:self.indexPath.row withObjectAtIndex:moveIndexPath.row];
    }
    self.block(self.dataArray);
}

检查截图是否到达边缘,并作出响应

- (BOOL)checkIfSnapshotMeetsEdge{
    CGFloat minY = CGRectGetMinY(self.snapView.frame);
    CGFloat maxY = CGRectGetMaxY(self.snapView.frame);
    if (minY < self.contentOffset.y) {
        self.autoScrollDirection = SnapshotMeetsEdgeTop;
        return YES;
    }
    if (maxY > self.bounds.size.height + self.contentOffset.y) {
        self.autoScrollDirection = SnapshotMeetsEdgeBottom;
        return YES;
    }
    return NO;
}

增加定时器自动滑动

/**
*  创建定时器并运行
*/
- (void)startAutoScrollTimer{
   if (self.autoScrollTimer == nil) {
       self.autoScrollTimer = [CADisplayLink displayLinkWithTarget:self selector:@selector(startAutoScroll)];
       [self.autoScrollTimer addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
   }
}
/**
*  停止定时器并销毁
*/
- (void)stopAutoScrollTimer{
   if (self.autoScrollTimer) {
       [self.autoScrollTimer invalidate];
       self.autoScrollTimer = nil;
   }
}
/**
*  开始自动滚动
*/
- (void)startAutoScroll{
   CGFloat pixelSpeed = 4;
   if (self.autoScrollDirection == SnapshotMeetsEdgeTop) {//向上滚动
       if (self.contentOffset.y > 0) {//向下滚动最大范围限制
           [self setContentOffset:CGPointMake(0, self.contentOffset.y - pixelSpeed)];
           self.snapView.center = CGPointMake(self.snapView.center.x, self.snapView.center.y - pixelSpeed);
       }
   }else{                                               //向下滚动
       if (self.contentOffset.y + self.bounds.size.height < self.contentSize.height) {//向下滚动最大范围限制
           [self setContentOffset:CGPointMake(0, self.contentOffset.y + pixelSpeed)];
           self.snapView.center = CGPointMake(self.snapView.center.x, self.snapView.center.y + pixelSpeed);
       }
   }
   
   /* 
   交换cell
    */
   NSIndexPath *exchangePath= [self indexPathForRowAtPoint:self.snapView.center];
   if (exchangePath) {
       [self updateDataWithIndexPath:exchangePath];
       [self moveRowAtIndexPath:self.indexPath toIndexPath:exchangePath];
       self.indexPath = exchangePath;
   }
}

相关文章

  • UITableViewCell拖拽移动两种实现方法

    1.UITableView协议方法的实现 使用协议方法相对比较简单。将tableview设置为可编辑状态,然后实现...

  • js实现拖拽

    ①鼠标按下+鼠标移动 → 拖拽②鼠标松开 → 无拖拽③鼠标偏移 → 拖拽距离 js实现 ① onmousedown...

  • IOS_SearchBar关键字搜索并标注为红色

    如下,实现相关代理方法, - (UITableViewCell *)tableView:(UITableView ...

  • Unity2D垃圾分类小游戏

    通过拖拽实例化的垃圾到制定的垃圾桶里,实现游戏逻辑。Unity实现对UI的拖拽。移动。

  • Android拖拽详解

    其实实现这种效果有两种方法: View.startDrag(), 然后给需要监听拖拽的控件setOnDragLis...

  • 可拖拽GridView代码解析

    分为三步来说明拖拽是怎么实现的。 1)如何让拖拽的Item来随着手指的移动而移动。 2)拖拽过程中相关item的移...

  • js拖拽html元素工具类

    复制就能用的拖拽js方法 原生js实现拖拽元素方法 使用(注意拖拽目标元素需绝对定位 position: 'abs...

  • POS-2017

    拖拽排序功能 实现方法: 使用jquery的Sortable功能可以实现拖拽功能 index页面 html部分 商...

  • Player移动控制2

    通过另外一种方式实现Player的移动控制: 通过EventSystems实现屏幕上的手指拖拽,实时记录手指移动的...

  • 实现可拖拽的RecycleView

    效果图 其实实现这种效果有两种方法: 1.View.startDrag(), 然后给需要监听拖拽的控件setOnD...

网友评论

  • 44e71b90e739:小小的建议 UIGestureRecognizerStateBegan 里面的reloaddata是异步的会造成下面取到的cell错乱哈
  • MT_suny:demo下载下来没有拖拽效果是什么情况
  • 哈哈我来了:demo,下载下来是空的:dizzy_face:
    yuandiLiao:谢谢提醒,重新提交了。

本文标题:UITableViewCell拖拽移动两种实现方法

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