iOS 可拖拽排序的UICollectionView
迪丽瓦拉
2025-06-01 15:53:46
0次

系统的UICollectionView和UITableView有提供在编辑态拖拽排序的功能,但是需要指定的EditStyle,而且还只能拖动排序按钮区域,大部分时候效果很难满足业务需求,因此我们需要定制可拖拽Cell的SDMovableCellCollectionView。文章最后附有Demo的Git地址,可查看完整代码。

实现思路

  1. 首先要给CollectionView添加长按手势;
  2. 然后手势开始时,找到当前手势坐标所在的startIndexPath,对cell生成snapshot,并隐藏此cell,接下来手势改变时都是改变snapshot在CollectionView中的位置;
  3. 手势改变时,snapshot的center跟随手势坐标变化,获取手势坐标所在的indexPath,并和startIndexPath交换位置;
  4. 手势结束时,cell显示,snapshot从父视图移除;
  5. 考虑拖拽边界情况;

手势核心代码

- (void)gestureBegan:(UILongPressGestureRecognizer *)gesture {CGPoint point = [gesture locationInView:gesture.view];NSIndexPath *selectedIndexPath = [self indexPathForItemAtPoint:point];if (!selectedIndexPath) {return;}UICollectionViewCell *cell = [self cellForItemAtIndexPath:selectedIndexPath];cell.alpha = 1.0;if (self.dataSource && [self.dataSource respondsToSelector:@selector(collectionView:canMoveItemAtIndexPath:)]) {if (![self.dataSource collectionView:self canMoveItemAtIndexPath:selectedIndexPath]) {//It is not allowed to move the cell, then shake it to prompt the user.if (self.canHintWhenCannotMove) {CAKeyframeAnimation *shakeAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform.translation.x"];shakeAnimation.duration = 0.25;shakeAnimation.values = @[@(-20), @(20), @(-10), @(10), @(0)];[cell.layer addAnimation:shakeAnimation forKey:@"shake"];}if (self.delegate && [self.delegate respondsToSelector:@selector(collectionView:tryMoveUnmovableCellAtIndexPath:)]) {[self.delegate collectionView:self tryMoveUnmovableCellAtIndexPath:selectedIndexPath];}UICollectionViewCell *cell = [self cellForItemAtIndexPath:selectedIndexPath];cell.alpha = 0.7;return;}}if (self.delegate && [self.delegate respondsToSelector:@selector(collectionView:willMoveCellAtIndexPath:)]) {[self.delegate collectionView:self willMoveCellAtIndexPath:selectedIndexPath];}if (_canEdgeScroll) {[self startEdgeScroll];}//Get a data source every time you moveif (self.dataSource && [self.dataSource respondsToSelector:@selector(dataSourceArrayInCollectionView:)]) {_tempDataSource = [self.dataSource dataSourceArrayInCollectionView:self];}_selectedIndexPath = selectedIndexPath;_startIndexPath = selectedIndexPath;if (self.canFeedback) {[self.generator prepare];[self.generator impactOccurred];}if (self.dataSource && [self.dataSource respondsToSelector:@selector(snapshotViewWithCell:)]) {UIView *snapView = [self.dataSource snapshotViewWithCell:cell];_snapshot = [self snapshotViewWithInputView:snapView];} else {_snapshot = [self snapshotViewWithInputView:cell];}if (self.delegate && [self.delegate respondsToSelector:@selector(collectionView:customizeMovalbeCell:)]) {[self.delegate collectionView:self customizeMovalbeCell:_snapshot];} else {_snapshot.layer.shadowColor = [UIColor grayColor].CGColor;_snapshot.layer.masksToBounds = NO;_snapshot.layer.cornerRadius = 0;_snapshot.layer.shadowOffset = CGSizeMake(-5, 0);_snapshot.layer.shadowOpacity = 0.4;_snapshot.layer.shadowRadius = 5;}//    _snapshot.frame = CGRectMake((cell.frame.size.width - _snapshot.frame.size.width)/2.0f, cell.frame.origin.y + (cell.frame.size.height - _snapshot.frame.size.height)/2.0, _snapshot.frame.size.width, _snapshot.frame.size.height);_snapshot.frame = cell.frame;[self addSubview:_snapshot];// 记录手势中心偏移self.gesturePointOffsetX = point.x - _snapshot.center.x;self.gesturePointOffsetY = point.y - _snapshot.center.y;cell.hidden = YES;if (self.delegate && [self.delegate respondsToSelector:@selector(collectionView:customizeStartMovingAnimation:fingerPoint:)]) {[self.delegate collectionView:self customizeStartMovingAnimation:_snapshot fingerPoint:point];} else {[UIView animateWithDuration:0.3 animations:^{self.snapshot.transform = CGAffineTransformScale(self.snapshot.transform, 1.1, 1.1);}];}
}- (void)gestureChanged:(UILongPressGestureRecognizer *)gesture {CGPoint point = [gesture locationInView:gesture.view];point.x -= self.gesturePointOffsetX;point.y -= self.gesturePointOffsetY;point = CGPointMake([self limitSnapshotCenterX:point.x], [self limitSnapshotCenterY:point.y]);//point = CGPointMake(_snapshot.center.x, [self limitSnapshotCenterY:point.y]);//Let the screenshot follow the gesture_snapshot.center = point;NSIndexPath *currentIndexPath = [self indexPathForItemAtPoint:point];if (!currentIndexPath) {return;}UICollectionViewCell *selectedCell = [self cellForItemAtIndexPath:_selectedIndexPath];selectedCell.hidden = YES;if (self.dataSource && [self.dataSource respondsToSelector:@selector(collectionView:canMoveItemAtIndexPath:)]) {if (![self.dataSource collectionView:self canMoveItemAtIndexPath:currentIndexPath]) {return;}}if (currentIndexPath && ![_selectedIndexPath isEqual:currentIndexPath]) {//Exchange data source and cell[self updateDataSourceAndCellFromIndexPath:_selectedIndexPath toIndexPath:currentIndexPath];if (self.delegate && [self.delegate respondsToSelector:@selector(collectionView:didMoveCellFromIndexPath:toIndexPath:)]) {[self.delegate collectionView:self didMoveCellFromIndexPath:_selectedIndexPath toIndexPath:currentIndexPath];}_selectedIndexPath = currentIndexPath;}
}- (void)gestureEndedOrCancelled:(UILongPressGestureRecognizer *)gesture {if (_canEdgeScroll) {[self stopEdgeScroll];}if (self.delegate && [self.delegate respondsToSelector:@selector(collectionView:endMoveCellAtIndexPath:)]) {[self.delegate collectionView:self endMoveCellAtIndexPath:_selectedIndexPath];}UICollectionViewCell *cell = [self cellForItemAtIndexPath:_selectedIndexPath];cell.alpha = 0.7;[UIView animateWithDuration:0.3 animations:^{self.snapshot.transform = CGAffineTransformIdentity;self.snapshot.frame = cell.frame;
//        self.snapshot.frame = CGRectMake((cell.frame.size.width - self.snapshot.frame.size.width)/2.0f, cell.frame.origin.y + (cell.frame.size.height - self.snapshot.frame.size.height)/2.0, self.snapshot.frame.size.width, self.snapshot.frame.size.height);} completion:^(BOOL finished) {cell.hidden = NO;[self.snapshot removeFromSuperview];self.snapshot = nil;}];// 延时后更新整个数据源dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{[self reloadData];});
}

Demo Git地址

SDMovableCellCollectionView

相关内容

热门资讯

家国同框 | 假期里的韩家窝村 10月5日清晨,来到韩家窝村,此村坐落于淄博周村南郊镇,墨水河畔,三面环山,是省级传统古村落,国家3...
假期余额不足 成都市民近郊游享... 10月6日,距离国庆假期结束仅剩一天。成都阳光普照,在百仁公园里,草坪上满是天幕与帐篷。市民们在城区...
散客占比近八成,九寨沟迈入“散... 封面新闻记者 杨金祝九寨沟景区正进入散客时代。10月6日,记者从九寨沟景区获悉,国庆假期,九寨沟迎来...
黄金周 中国游 | “便利政策... 央视网消息:上海正全力打造“中国入境游第一站”,并推动入境游从赏景购物转向深度体验。在上海,外国游客...
通讯|布哈拉全城都知道中国放长...   新华社塔什干10月6日电 通讯|布哈拉全城都知道中国放长假了——探访中亚跨境旅游热  新华社记者...
奔县游|美食好物:小城烟火藏文...   眼下,以沉浸式、慢体验、近短途为特点的“奔县游”持续升温。地处江淮分水岭的安徽省来安县,立足半山...
专访丨约旦多措并举吸引中国游客... 新华社安曼10月6日电 专访|约旦多措并举吸引中国游客——访约旦旅游和文物大臣希贾津新华社记者何奕萍...
国庆别去外滩了,长宁才是隐藏款 国庆的上海,外滩是人山人海。但真正好逛的地方,不仅仅在最热闹的地界。长宁区延安西路1262号,上生·...
大渡河畔红色地标引游客 标题:赓续长征精神 奋进复兴征程|大渡河畔红色地标引游客国庆假期,各地游客来到位于四川省雅安市石棉县...
滇池东岸美食风物季丨10月6日... 秋日湖畔,音浪不息2026滇池东岸美食风物季持续火热10月6日滇池东岸将带来旷野歌者王金永的昆明专场...