因工作需求,处理上传多个图片,并且可以预览换位置的功能, 就写了一个基于collectionView 编辑模式的demo, 原理很简单,主要是处理当图片小于9张时,会有一个 ➕ 的item, 并且这个 ➕ item 不能被拖动到其他位置
下面直接开始demo
- 首先在视图添加一个collectionView, 这个步骤就省略了
- 给collectionView 增加长按手势,来触发编辑模式
//此处给其增加长按手势,用此手势触发cell移动效果
UILongPressGestureRecognizer *longGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handlelongGesture:)];
[_collectionView addGestureRecognizer:longGesture];
-
为了处理最后一个位置cell,我们要声明一个cell, 并且保存最后一个位置的cell
// 声明最后一个cell
@property (nonatomic, strong) UICollectionViewCell *lastCell; // 在 - (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath; 方法中 保存最后一个cell if (indexPath.row == self.dataSource.count - 1) { self.lastCell = 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];
if (self.dataSource.count < 9) {
NSIndexPath *temp = [self.collectionView indexPathForCell:self.lastCell];
NSIndexPath *end = [NSIndexPath indexPathForRow:self.dataSource.count - 1 inSection:0];
if (temp.row != end.row) {
// 交换我们记录的最后一个位置的cell 和 当前最后一个位置的cell
[self.collectionView moveItemAtIndexPath:temp toIndexPath:end];
}
}
}
break;
default:
{
[self.collectionView cancelInteractiveMovement];
}
break;
}
}
```
- 另外,为了collectionView 可以编辑,还需要实现以下collectionView的代理方法
- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath{
//返回YES允许其item移动
if (indexPath.row == self.dataSource.count - 1 && self.dataSource.count < 9) {
return NO;
} return YES;
}
- 在以下代理方法中,当cell移动了以后,交换DataSource的里数据的位置
```
- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
NSNumber *num = self.dataSource[sourceIndexPath.item];
if (destinationIndexPath.row != self.dataSource.count - 1) {
[self.dataSource removeObjectAtIndex:sourceIndexPath.item];
[self.dataSource insertObject:num atIndex:destinationIndexPath.item];
}
}
```
## 到这里 我们就完成了这个demo 完工~~
## 最后附上GitHub 地址,欢迎大家下载提意见,喜欢的给✨啊
[ccollectionView编辑](https://github.com/qq360078224/collectionView-edti.git)