美文网首页
学习笔记 - CollectionView 拖拽重拍

学习笔记 - CollectionView 拖拽重拍

作者: 听雨花春风 | 来源:发表于2016-07-08 07:33 被阅读106次
  1. 给collectionView添加一个长按手势
       //用此手势触发cell移动效果
     UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handlelongGesture:)];
     [_collectionView addGestureRecognizer:longPress];
    
  2. 根据当前手势的状态来判断如何处理cell
//移动cell
- (void)handlelongGesture:(UILongPressGestureRecognizer *)longGesture{

    //判断手势状态
    switch (longGesture.state) {
        case UIGestureRecognizerStateBegan:{
            //判断手势落点位置是否在路径上
            NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:[longGesture locationInView:self.collectionView]];
            if (indexPath == nil) {
                break;
            }
            //在路径上则开始移动该路径上的cell
            [self.collectionView beginInteractiveMovementForItemAtIndexPath:indexPath];
        }
            break;
        case UIGestureRecognizerStateChanged:
            //移动过程当中随时更新cell位置
            [self.collectionView updateInteractiveMovementTargetPosition:[longGesture locationInView:self.collectionView]];
            break;
        case UIGestureRecognizerStateEnded:
            //移动结束后关闭cell移动
            [self.collectionView endInteractiveMovement];
            break;
        default:
            [self.collectionView cancelInteractiveMovement];
            break;
    }

}

3.在代理方法中实现一些配置

- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath*)destinationIndexPath {
    //取出源item数据
    id objc = [_datalist objectAtIndex:sourceIndexPath.item];
    //从资源数组中移除该数据
    [_datalist removeObject:objc];
    //将数据插入到资源数组中的目标位置上
    [_datalist insertObject:objc atIndex:destinationIndexPath.item];
}

-(BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath{

    return  YES;

}


相关文章

网友评论

      本文标题:学习笔记 - CollectionView 拖拽重拍

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