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];
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值