UITableView長按拖動排序(支持不同行高,不同section間交換)

效果圖:

DHDragableCellTableView.gif

github下載地址:DHDragableCellTableView

使用

將tableView繼承與DHDragableCellTableView并遵循協(xié)議DHDragableCellTableViewDataSource,DHDragableCellTableViewDelegate

#pragma mark - DHDragableCellTableViewDataSource
- (NSArray *)dataSourceArrayInTableView:(DHDragableCellTableView *)tableView{
    return self.dataSource.copy;//數(shù)據(jù)源
}

- (void)tableView:(DHDragableCellTableView *)tableView newDataSourceArrayAfterMove:(NSArray *)newDataSourceArray{
    self.dataSource = newDataSourceArray.mutableCopy;//返回的數(shù)據(jù)源
    [self.tableView reloadData];
}

實現(xiàn):

大概思路,為UITableView添加長按手勢,長按后給選擇的cell截圖并隱藏選擇的cell,讓截圖跟隨手勢移動

1.添加手勢

/**
 添加手勢
 */
- (void)dh_addGesture
{
    _gesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(dh_processGesture:)];
    _gesture.minimumPressDuration = _gestureMinimumPressDuration;
    [self addGestureRecognizer:_gesture];
}

2.監(jiān)聽手勢狀態(tài)

- (void)dh_processGesture:(UILongPressGestureRecognizer *)gesture
{
    switch (gesture.state) {
        case UIGestureRecognizerStateBegan:
        {
            [self dh_gestureBegan:gesture];
        }
            break;
        case UIGestureRecognizerStateChanged:
        {
            if (!_canEdgeScroll) {
                [self dh_gestureChanged:gesture];
            }
        }
            break;
        case UIGestureRecognizerStateEnded:
        case UIGestureRecognizerStateCancelled:
        {
            [self dh_gestureEndedOrCancelled:gesture];
        }
            break;
        default:
            break;
    }
}

3.開始拖動

- (void)dh_gestureBegan:(UILongPressGestureRecognizer *)gesture
{
    CGPoint point = [gesture locationInView:gesture.view];
    self.lastPoint = point;
    NSIndexPath *selectedIndexPath = [self indexPathForRowAtPoint:point];
    if (!selectedIndexPath) {
        return;
    }
    if (self.delegate && [self.delegate respondsToSelector:@selector(tableView:willMoveCellAtIndexPath:)]) {
        [self.delegate tableView:self willMoveCellAtIndexPath:selectedIndexPath];
    }
    if (_canEdgeScroll) {
        //開啟邊緣滾動
        [self dh_startEdgeScroll];
    }
    //每次移動開始獲取一次數(shù)據(jù)源
    if (self.dataSource && [self.dataSource respondsToSelector:@selector(dataSourceArrayInTableView:)]) {
        _tempDataSource = [self.dataSource dataSourceArrayInTableView:self].mutableCopy;
    }
    _selectedIndexPath = selectedIndexPath;
    UITableViewCell *cell = [self cellForRowAtIndexPath:selectedIndexPath];
    _tempView = [self dh_snapshotViewWithInputView:cell];
    if (_drawMovalbeCellBlock) {
        //將_tempView通過block讓使用者自定義
        _drawMovalbeCellBlock(_tempView);
    }else {
        //配置默認樣式
        _tempView.layer.shadowColor = [UIColor grayColor].CGColor;
        _tempView.layer.masksToBounds = NO;
        _tempView.layer.cornerRadius = 0;
        _tempView.layer.shadowOffset = CGSizeMake(-5, 0);
        _tempView.layer.shadowOpacity = 0.4;
        _tempView.layer.shadowRadius = 5;
    }
    _tempView.frame = cell.frame;
    [self addSubview:_tempView];
    //隱藏cell
    cell.hidden = YES;
    [UIView animateWithDuration:kDH_DragableCellAnimationTime animations:^{
        _tempView.center = CGPointMake(_tempView.center.x, point.y);
    }];
}

4.拖動 這里的_toBottom是int類型用來判斷手勢是向哪一個方向拖動,然后根據(jù)拖動的cell跟要交換的cell的中心點進行比較,判斷是否交換

- (void)dh_gestureChanged:(UILongPressGestureRecognizer *)gesture
{
    CGPoint point = [gesture locationInView:gesture.view];
    //判斷拖動的方向
    if (point.y - self.lastPoint.y > 0) {
        _toBottom = 1;//向下拖
    }else if(point.y - self.lastPoint.y < 0){
        _toBottom = -1;//向上拖
    }else{
        _toBottom = 0;
    }
    self.lastPoint = point;
    NSIndexPath *currentIndexPath = [self indexPathForRowAtPoint:point];
    if (currentIndexPath && ![_selectedIndexPath isEqual:currentIndexPath]) {
        UITableViewCell *cell = [self cellForRowAtIndexPath:_selectedIndexPath];
        UITableViewCell *cell1 = [self cellForRowAtIndexPath:currentIndexPath];
        //將拖動的cell跟要交換的cell的centerY進行比較
        if ((_toBottom == 1 && (point.y+cell.frame.size.height/2) >= CGRectGetMaxY(cell1.frame) && (CGRectGetMaxY(cell1.frame) >= CGRectGetMaxY(cell.frame))) || ((_toBottom == -1 && (point.y-cell.frame.size.height/2) <= CGRectGetMinY(cell1.frame)) && (CGRectGetMinY(cell1.frame) <= CGRectGetMinY(cell.frame)))) {
            //交換數(shù)據(jù)源和cell
            [self dh_updateDataSourceAndCellFromIndexPath:_selectedIndexPath toIndexPath:currentIndexPath];
            if (self.delegate && [self.delegate respondsToSelector:@selector(tableView:didMoveCellFromIndexPath:toIndexPath:)]) {
                [self.delegate tableView:self didMoveCellFromIndexPath:_selectedIndexPath toIndexPath:currentIndexPath];
            }
            _selectedIndexPath = currentIndexPath;
        }
    }
    //讓截圖跟隨手勢
    _tempView.center = CGPointMake(_tempView.center.x, point.y);
}

5.交換數(shù)據(jù)跟cell的位置 為了在不同行高交換時cell不變形,交換后要立刻reloadData,再通過對兩個cell截圖,用截圖來模擬交換的動畫

/**
 交換數(shù)據(jù)源 跟 cell的位置
 */
- (void)dh_updateDataSourceAndCellFromIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
    if ([self numberOfSections] == 1) {
        //只有一組
        [_tempDataSource exchangeObjectAtIndex:fromIndexPath.row withObjectAtIndex:toIndexPath.row];
        //交換cell
        [self moveRowAtIndexPath:fromIndexPath toIndexPath:toIndexPath];
    }else {
        //有多組
        id fromData = _tempDataSource[fromIndexPath.section][fromIndexPath.row];
        id toData = _tempDataSource[toIndexPath.section][toIndexPath.row];
        NSMutableArray *fromArray = [_tempDataSource[fromIndexPath.section] mutableCopy];
        NSMutableArray *toArray = [_tempDataSource[toIndexPath.section] mutableCopy];
        [fromArray replaceObjectAtIndex:fromIndexPath.row withObject:toData];
        [toArray replaceObjectAtIndex:toIndexPath.row withObject:fromData];
        [_tempDataSource replaceObjectAtIndex:fromIndexPath.section withObject:fromArray];
        [_tempDataSource replaceObjectAtIndex:toIndexPath.section withObject:toArray];
        //交換cell
        [self beginUpdates];
        
        [self moveRowAtIndexPath:fromIndexPath toIndexPath:toIndexPath];
        [self moveRowAtIndexPath:toIndexPath toIndexPath:fromIndexPath];
        [self endUpdates];
    }
    //交換數(shù)據(jù)源后reloadData
    [self reloadData];
    //返回交換后的數(shù)據(jù)源
    if (self.dataSource && [self.dataSource respondsToSelector:@selector(tableView:newDataSourceArrayAfterMove:)]) {
        [self.dataSource tableView:self newDataSourceArrayAfterMove:_tempDataSource.copy];
    }
    //此處用兩個cell的截圖實現(xiàn)交換的動畫
    UITableViewCell *cell = [self cellForRowAtIndexPath:fromIndexPath];
    cell.hidden = NO;
    UITableViewCell *cell1 = [self cellForRowAtIndexPath:toIndexPath];
    cell1.hidden = YES;
    UIView *tmpCell = [self dh_snapshotViewWithInputView:cell];
    cell.hidden = YES;
    tmpCell.frame = cell1.frame;
    if (_toBottom == -1) {//向上
        tmpCell.frame = CGRectMake(0, CGRectGetMinY(cell1.frame), cell.frame.size.width, cell.frame.size.height);
        [self insertSubview:tmpCell belowSubview:_tempView];
    }else if (_toBottom == 1) {//向下
        tmpCell.frame = CGRectMake(0, CGRectGetMaxY(cell1.frame)-cell.frame.size.height, cell.frame.size.width, cell.frame.size.height);
        [self insertSubview:tmpCell belowSubview:_tempView];
    }else{
    }
    
    [UIView animateWithDuration:0.2 animations:^{
        tmpCell.frame = cell.frame;
    }completion:^(BOOL finished) {
        cell.hidden = NO;
        [tmpCell removeFromSuperview];
    }];
}

6.邊緣滾動處理

- (void)dh_startEdgeScroll
{
    _edgeScrollTimer = [CADisplayLink displayLinkWithTarget:self selector:@selector(dh_processEdgeScroll)];
    [_edgeScrollTimer addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
}

- (void)dh_processEdgeScroll
{
    [self dh_gestureChanged:_gesture];
    CGFloat minOffsetY = self.contentOffset.y + _edgeScrollRange;
    CGFloat maxOffsetY = self.contentOffset.y + self.bounds.size.height - _edgeScrollRange;
    CGPoint touchPoint = _tempView.center;
    //處理上下達到極限之后不再滾動tableView,其中處理了滾動到最邊緣的時候,當前處于edgeScrollRange內(nèi),但是tableView還未顯示完,需要顯示完tableView才停止?jié)L動
    if (touchPoint.y < _edgeScrollRange) {
        if (self.contentOffset.y <= 0) {
            return;
        }else {
            if (self.contentOffset.y - 1 < 0) {
                return;
            }
            [self setContentOffset:CGPointMake(self.contentOffset.x, self.contentOffset.y - 1) animated:NO];
            _tempView.center = CGPointMake(_tempView.center.x, _tempView.center.y - 1);
        }
    }
    if (touchPoint.y > self.contentSize.height - _edgeScrollRange) {
        if (self.contentOffset.y >= self.contentSize.height - self.bounds.size.height) {
            return;
        }else {
            if (self.contentOffset.y + 1 > self.contentSize.height - self.bounds.size.height) {
                return;
            }
            [self setContentOffset:CGPointMake(self.contentOffset.x, self.contentOffset.y + 1) animated:NO];
            _tempView.center = CGPointMake(_tempView.center.x, _tempView.center.y + 1);
        }
    }
    //處理滾動
    CGFloat maxMoveDistance = 20;
    if (touchPoint.y < minOffsetY) {
        //cell在往上移動
        CGFloat moveDistance = (minOffsetY - touchPoint.y)/_edgeScrollRange*maxMoveDistance;
        [self setContentOffset:CGPointMake(self.contentOffset.x, self.contentOffset.y - moveDistance) animated:NO];
        _tempView.center = CGPointMake(_tempView.center.x, _tempView.center.y - moveDistance);
    }else if (touchPoint.y > maxOffsetY) {
        //cell在往下移動
        CGFloat moveDistance = (touchPoint.y - maxOffsetY)/_edgeScrollRange*maxMoveDistance;
        [self setContentOffset:CGPointMake(self.contentOffset.x, self.contentOffset.y + moveDistance) animated:NO];
        _tempView.center = CGPointMake(_tempView.center.x, _tempView.center.y + moveDistance);
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容