美文网首页
UICollectionView Cell 任意拖拽重排

UICollectionView Cell 任意拖拽重排

作者: 土豆灬烤薯片 | 来源:发表于2019-01-08 15:33 被阅读0次

    1.首先给你的CollectionView 添加长按手势:

    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPressGesture:)];

    [self.collectionview addGestureRecognizer:longPress];

    2.手势中处理只支持ios9之后

    - (void)handleLongPressGesture:(UILongPressGestureRecognizer*)recognizer{

        switch(recognizer.state) {

            case UIGestureRecognizerStateBegan: {

                NSIndexPath *indexPath = [self.collection indexPathForItemAtPoint:[recognizer locationInView:self.collection]];

                if(nil== indexPath) {

                    break;

                }

                // 在路径上则开始移动该路径上的cell

                [self.collection beginInteractiveMovementForItemAtIndexPath:indexPath];

                break;

            }

            case UIGestureRecognizerStateChanged: {

                // 移动过程当中随时更新cell位置

                [self.collection updateInteractiveMovementTargetPosition:[recognizer locationInView:self.collection]];

                break;

            }

            case UIGestureRecognizerStateEnded: {

                // 移动结束后关闭cell移动

                [self.collection endInteractiveMovement];

                break;

            }

            default: {

                [self.collection cancelInteractiveMovement];

                break;

            }

        }

    }

    3.添加collectionviewitem的移动方法

    - (void)collectionView:(UICollectionView*)collectionView moveItemAtIndexPath:(NSIndexPath*)sourceIndexPath toIndexPath:(NSIndexPath*)destinationIndexPath{

        BOOLcanChange =self.dataArray.count> sourceIndexPath.item&&self.dataArray.count> destinationIndexPath.item;

        if(canChange) {

            [self handleDatasourceExchangeWithSourceIndexPath:sourceIndexPath destinationIndexPath:destinationIndexPath];

        }

    }

    - (void)handleDatasourceExchangeWithSourceIndexPath:(NSIndexPath*)sourceIndexPath destinationIndexPath:(NSIndexPath*)destinationIndexPath{

        NSMutableArray *tempArr = [self.dataArray mutableCopy];

        NSIntegeractiveRange = destinationIndexPath.item- sourceIndexPath.item;

        BOOLmoveForward = activeRange >0;

        NSIntegeroriginIndex =0;

        NSIntegertargetIndex =0;

        for(NSIntegeri =1; i <=labs(activeRange); i ++) {

            NSIntegermoveDirection = moveForward?1:-1;

            originIndex = sourceIndexPath.item+ i*moveDirection;

            targetIndex = originIndex  -1*moveDirection;

            [tempArrexchangeObjectAtIndex:originIndexwithObjectAtIndex:targetIndex];

        }

    }

    相关文章

      网友评论

          本文标题:UICollectionView Cell 任意拖拽重排

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