UICollectionView实现拖拽编辑

需求

前段时间我们公司要实现一个类似网易新闻的栏目编辑功能,于是乎我开始在网上查阅各种资料,但是找到的demo都不尽如人意。现在这个功能已经初步完成了,我觉得还是有必要分享一下这个实现历程的。

实现

  • Interactive Reordering(iOS9 UICollectionView新特性)

使用这种方法就很容易实现这个功能。你需要在UICollectionView上添加一个长按手势,然后在手势的响应方法里面分别让begin,move,end,cancel对应调用下面这四个方法,就能实现拖拽cell这个功能了。

- (BOOL)beginInteractiveMovementForItemAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(9_0); 
- (void)updateInteractiveMovementTargetPosition:(CGPoint)targetPosition NS_AVAILABLE_IOS(9_0);
- (void)endInteractiveMovement NS_AVAILABLE_IOS(9_0);
- (void)cancelInteractiveMovement NS_AVAILABLE_IOS(9_0);

最后还要处理拖拽后的数据,就是datasource下面这个方法。

- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath*)destinationIndexPath NS_AVAILABLE_IOS(9_0);

这种方式我就不再赘述了,网上能找到比较多博客讲解。我用上面的方法实现了这个功能之后,效果确实还是不错。然并卵,公司现在的应用还是兼容iOS8的。

  • moveItemAtIndexPath:toIndexPath

没错!就是上面这个方法可以帮我们在iOS9之前实现这个效果。其实看过Interactive Reordering这种实现方式后,我们也是可以通过moveitemto这个方法来自己实现的。

不过我不喜欢通过长按来实现拖拽,所以我尝试了一下在cell里面回传touch事件。首先我需要给cell添加一个枚举和协议。

typedef NS_ENUM(NSUInteger, SCCatalogMenuCellTouchType) {
    SCCatalogMenuCellTouchBegan,
    SCCatalogMenuCellTouchMoved,
    SCCatalogMenuCellTouchEnded,
    SCCatalogMenuCellTouchCancelled
};

@protocol SCCatalogMenuCellTouchProtocol 
- (void)dealWithCatalogMenuCellTouch:(UITouch *)touch AndType:(SCCatalogMenuCellTouchType)type;
@end

然后在到cell的实现文件中回传touch事件。这里我选择了使用响应链回传。

- (UIResponder *)touchResponder {
    UIResponder *next = self.nextResponder;
    while (next != nil) {
        if ([next respondsToSelector:@selector(dealWithCatalogMenuCellTouch:AndType:)]) {
            return (UIResponder *)next;
        }
        next = next.nextResponder;
    }
    return nil;
}
#pragma mark - 传递cell的touch事件。
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
    [[self touchResponder] dealWithCatalogMenuCellTouch:[touches anyObject] AndType:SCCatalogMenuCellTouchBegan];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesMoved:touches withEvent:event];
    [[self touchResponder] dealWithCatalogMenuCellTouch:[touches anyObject] AndType:SCCatalogMenuCellTouchMoved];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesEnded:touches withEvent:event];
    [[self touchResponder] dealWithCatalogMenuCellTouch:[touches anyObject] AndType:SCCatalogMenuCellTouchEnded];
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesCancelled:touches withEvent:event];
    [[self touchResponder] dealWithCatalogMenuCellTouch:[touches anyObject] AndType:SCCatalogMenuCellTouchCancelled];
}

最后我们来看一下这个协议的实现。

#pragma mark - 拖拽cell
- (void)dealWithCatalogMenuCellTouch:(UITouch *)touch AndType:(SCCatalogMenuCellTouchType)type {
    if (!self.editing) {
        return;
    }
    __weak typeof(self) weakSelf = self;
    static SCCatalogMenuCell *cell;
    switch (type) {
        case SCCatalogMenuCellTouchBegan:{
            self.collectionView.panGestureRecognizer.enabled = NO;
            CGPoint point = [touch locationInView:self.collectionView];
            //在touch事件开始的时候获取起始的indexpath
            self.sourceIndexPath = [self.collectionView indexPathForItemAtPoint:point];
            if (self.sourceIndexPath.row == 0) {
                return;
            }
            //拿到起始indexpath对应的视图,隐藏子视图
            cell = (SCCatalogMenuCell *)[self.collectionView cellForItemAtIndexPath:self.sourceIndexPath];
            [cell hideSubViews];
            //使用一个另外一个手动创建的cell来占位
            self.fakeCell.frame = cell.frame;
            self.fakeCell.mainTitle.text = cell.mainTitle.text;
            [self.fakeCell magnifyMainTitleSize];
            [self.collectionView addSubview:self.fakeCell];
            //记录所有item的attributes
            [self.cellAttributesArray removeAllObjects];
            for (int i = 0; i < self.currentArray.count; i++) {
                [self.cellAttributesArray addObject:[_collectionView layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForItem:i inSection:0]]];
            }
        }
            break;
        case SCCatalogMenuCellTouchMoved:{
            if (self.sourceIndexPath.row == 0) {
                return;
            }
            //这里我们这个虚假的cell来代替起始位置的cell做移动
            self.fakeCell.center = [touch locationInView:_collectionView];
            //为了模仿interective recording还需要添加一个timer来处理我们手势位置到达上下边界时需要移动collectionview
            if ((self.fakeCell.center.y >= self.collectionView.contentOffset.y && self.fakeCell.center.y < self.collectionView.contentOffset.y + 25) || (self.fakeCell.center.y > self.collectionView.contentOffset.y + self.collectionView.frame.size.height - 25 && self.fakeCell.center.y <= self.collectionView.contentOffset.y + self.collectionView.frame.size.height)) {
                [self startTimer];
            }
            else {
                [self pauseTimer];
            }
            //这里使需要注意的地方,超出可视范围的地方需要屏蔽掉,会出bug。
            if (self.fakeCell.center.y > self.collectionView.frame.size.height + self.collectionView.contentOffset.y || self.fakeCell.center.y < self.collectionView.contentOffset.y) {
                break;
            }
            //这个是检测移动的方法,在timer的回调中也是要复用的
            [self checkAndMoveIndexPath];
        }
            break;
        case SCCatalogMenuCellTouchEnded:{
            if (self.sourceIndexPath.row == 0) {
                self.sourceIndexPath = nil;
                return;
            }
            [self pauseTimer];
            self.collectionView.panGestureRecognizer.enabled = YES;
            if (!self.destinationIndexPath) {
                //这里处理有目标indexPath的情况
                [UIView animateWithDuration:0.2 animations:^{
                    weakSelf.fakeCell.center = [_collectionView layoutAttributesForItemAtIndexPath:self.sourceIndexPath].center;
                } completion:^(BOOL finished) {
                    [weakSelf.fakeCell restoreMainTitleSize];
                    [weakSelf.fakeCell removeFromSuperview];
                    [cell showSubViews];
                    weakSelf.sourceIndexPath = nil;
                }];
            }
            else {
                //如果有目标indexPath,更新一下移动后的数据
                id obj = self.currentArray[self.sourceIndexPath.row];
                [self.currentArray removeObjectAtIndex:self.sourceIndexPath.row];
                [self.currentArray insertObject:obj atIndex:self.destinationIndexPath.row];
                [UIView animateWithDuration:0.2 animations:^{
                    weakSelf.fakeCell.center = [_collectionView layoutAttributesForItemAtIndexPath:self.destinationIndexPath].center;
                } completion:^(BOOL finished) {
                    [weakSelf.fakeCell restoreMainTitleSize];
                    [weakSelf.fakeCell removeFromSuperview];
                    [cell showSubViews];
                    weakSelf.destinationIndexPath = nil;
                    weakSelf.sourceIndexPath = nil;
                }];
            }
        }
            break;
        case SCCatalogMenuCellTouchCancelled:{
            //这里处理手势取消的情况
            if (self.sourceIndexPath.row == 0) {
                self.sourceIndexPath = nil;
                return;
            }
            [self pauseTimer];
            self.collectionView.panGestureRecognizer.enabled = YES;
            [UIView animateWithDuration:0.2 animations:^{
                weakSelf.fakeCell.center = [_collectionView layoutAttributesForItemAtIndexPath:self.sourceIndexPath].center;
            } completion:^(BOOL finished) {
                [weakSelf.fakeCell restoreMainTitleSize];
                [weakSelf.fakeCell removeFromSuperview];
                [cell showSubViews];
                weakSelf.sourceIndexPath = nil;
            }];
        }
            break;
        default:
            break;
    }
}
#pragma mark - cell移动位置
- (void)checkAndMoveIndexPath {
    for (UICollectionViewLayoutAttributes *attributes in self.cellAttributesArray) {
        if (attributes.indexPath.row != 0 && CGRectContainsPoint(attributes.frame, self.fakeCell.center)) {
            if (!self.destinationIndexPath && attributes.indexPath != self.sourceIndexPath) {
                [self.collectionView moveItemAtIndexPath:self.sourceIndexPath toIndexPath:attributes.indexPath];
                self.destinationIndexPath = attributes.indexPath;
            }
            else if (self.destinationIndexPath && attributes.indexPath != self.destinationIndexPath) {
                [self.collectionView moveItemAtIndexPath:self.destinationIndexPath toIndexPath:attributes.indexPath];
                self.destinationIndexPath = attributes.indexPath;
            }
        }
    }
}
#pragma mark - timer处理
- (void)responseToTimer {
    if (self.fakeCell.center.y < self.collectionView.contentOffset.y + 25) {
        if (self.collectionView.contentOffset.y < 5) {
            self.fakeCell.center = CGPointMake(self.fakeCell.center.x, self.fakeCell.center.y - self.collectionView.contentOffset.y);
            self.collectionView.contentOffset = CGPointZero;
        }
        else {
            self.fakeCell.center = CGPointMake(self.fakeCell.center.x, self.fakeCell.center.y - 5);
            self.collectionView.contentOffset = CGPointMake(0, self.collectionView.contentOffset.y - 5);
        }
        [self checkAndMoveIndexPath];
    }
    else if (self.fakeCell.center.y > self.collectionView.contentOffset.y + self.collectionView.frame.size.height - 25) {
        if (self.collectionView.contentOffset.y + self.collectionView.frame.size.height > self.collectionView.contentSize.height - 5) {
            self.fakeCell.center = CGPointMake(self.fakeCell.center.x, self.fakeCell.center.y + (self.collectionView.contentSize.height - self.collectionView.contentOffset.y - self.collectionView.frame.size.height));
            self.collectionView.contentOffset = CGPointMake(0, self.collectionView.contentSize.height - self.collectionView.frame.size.height);
        }
        else {
            self.fakeCell.center = CGPointMake(self.fakeCell.center.x, self.fakeCell.center.y + 5);
            self.collectionView.contentOffset = CGPointMake(0, self.collectionView.contentOffset.y + 5);
        }
        [self checkAndMoveIndexPath];
    }
}

这就是我实现的思路,大家可以参考一下。代码传送门在这里。

你可能感兴趣的:(UICollectionView实现拖拽编辑)