一、拖动其中的cell
UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressMethod:)]; longPressGesture.minimumPressDuration=0.3f; [self.collectViewaddGestureRecognizer:longPressGesture];
#pragma mark- 长按手势方法
-(void)longPressMethod:(UILongPressGestureRecognizer*)longPress {
//1 获取手势触发点Point
CGPointpoint = [longPresslocationInView:self.collectView];
NSIndexPath *path = [self getDragingToIndexPathWithPoint:point];
if(!path || path.section!=0){
return;
}
BOOLisInside = [self.collectViewpointInside:pointwithEvent:nil];
if(!isInside){
[_collectView cancelInteractiveMovement];
return;
}
NSIndexPath *indexPath = [self.collectView indexPathForItemAtPoint:point];
// 根据长按手势的状态进行处理。
switch(longPress.state) {
case UIGestureRecognizerStateBegan:
// 当没有点击到cell的时候不进行处理
if(!indexPath) {
break;
}
// 开始移动
[_collectView beginInteractiveMovementForItemAtIndexPath:indexPath];
break;
case UIGestureRecognizerStateChanged:
// 移动过程中更新位置坐标
[_collectView updateInteractiveMovementTargetPosition:point];
break;
case UIGestureRecognizerStateEnded:
// 停止移动调用此方法
[_collectView endInteractiveMovement];
break;
default:
// 取消移动
[_collectView cancelInteractiveMovement];
break;
}
}
-(NSIndexPath*)getDragingToIndexPathWithPoint:(CGPoint)point {
NSIndexPath*indexPahtTemp =nil;
//获取当前可见cell的indexPaht组
NSArray *indexPahtArr = [self.collectView indexPathsForVisibleItems];
for(NSIndexPath*indexPathinindexPahtArr) {
//下半部分不用排序
if(indexPath.section>0) {
continue;
}
//上半部分中 找出点所在的indexPath
BOOLisContains =CGRectContainsPoint([self.collectViewcellForItemAtIndexPath:indexPath].frame, point);
if(isContains ==YES) {
indexPahtTemp = indexPath;
break;
}
}
returnindexPahtTemp;
}
-(void)collectionView:(UICollectionView*)collectionViewmoveItemAtIndexPath:(NSIndexPath*)sourceIndexPathtoIndexPath:(NSIndexPath*)destinationIndexPath {
if(destinationIndexPath.section!=0){
[self.collectViewmoveItemAtIndexPath:destinationIndexPathtoIndexPath:sourceIndexPath];
return;
}
// 这里做数据交换
WNShortcutModel *model = [self.viewModel.sectionModels objectAtIndex:0]; WNShortcutSingleModel *obj = [model.singleModels objectAtIndex:sourceIndexPath.row];
NSMutableArray *mutableModels = [NSMutableArray arrayWithArray:model.singleModels];
[mutableModelsremoveObject:obj];
[mutableModelsinsertObject:objatIndex:destinationIndexPath.row];
model.singleModels= mutableModels;
[self.viewModel.sectionModels removeObjectAtIndex:0];
[self.viewModel.sectionModels insertObject:model atIndex:0];
[self changeShortCutApp];
}
有两点需要注意
1、cell拖动到collectionView外部怎么处理。
2、cell拖动的范围需要处理,是否只允许第一个section的cell拖动。
二、cell的布局,背景色等设置
collectionView没有tableView使用方便可以直接根据系统的API设置背景色圆角等。
一般我们需要重写UICollectionViewFlowLayout、UICollectionReusableView、 UICollectionViewLayoutAttributes。
网友评论