UICollectionView Cell 任意拖拽重排

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];

    }

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容