IOS CollectionView 拖拽移动

collection 增加长按手势

   //添加长按的手势
     UILongPressGestureRecognizer *longPress=[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPress:)];
   [collectionView addGestureRecognizer:longPress];
- (void)longPress:(UIGestureRecognizer *)longPress {
    //获取点击在collectionView的坐标
    CGPoint point=[longPress locationInView:self.collectionView];
    //从长按开始
    if (longPress.state == UIGestureRecognizerStateBegan) {

        NSIndexPath *indexPath=[self.collectionView indexPathForItemAtPoint:point];
        [self.collectionView beginInteractiveMovementForItemAtIndexPath:indexPath];
        //长按手势状态改变
    } else if(longPress.state==UIGestureRecognizerStateChanged) {
        [self.collectionView updateInteractiveMovementTargetPosition:point];
        //长按手势结束
    } else if (longPress.state==UIGestureRecognizerStateEnded) {

        [self.collectionView endInteractiveMovement];

        //其他情况
    } else {
        [self.collectionView cancelInteractiveMovement];
    }

}
- (NSIndexPath *)collectionView:(UICollectionView *)collectionView targetIndexPathForMoveFromItemAtIndexPath:(NSIndexPath *)originalIndexPath toProposedIndexPath:(NSIndexPath *)proposedIndexPath {
    /* 两个indexpath参数, 分别代表源位置, 和将要移动的目的位置*/
    //-1 是为了不让最后一个可以交换位置
    if (proposedIndexPath.item == (_dataArrays.count - 1)) {
        //初始位置
        return originalIndexPath;
    } else {
    //-1 是为了不让最后一个可以交换位置
        if (originalIndexPath.item == (_dataArrays.count - 1)) {
            return originalIndexPath;
        }
//      移动后的位置
        return proposedIndexPath;
    }
}
-(void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
        //记录要移动的数据
        id object= self.dataArrays[sourceIndexPath.item];
        //删除要移动的数据
        [self.dataArrays removeObjectAtIndex:sourceIndexPath.item];
        //添加新的数据到指定的位置
        [self.dataArrays insertObject:object atIndex:destinationIndexPath.item];
}

猜你喜欢

转载自blog.csdn.net/goods_boy/article/details/70767951
今日推荐