IOS CollectionView拖拽移动

释放双眼,带上耳机,听听看~!

collection 增加长按手势

   //添加长按的手势
UILongPressGestureRecognizer *longPress=[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPress:)];
[collectionView addGestureRecognizer:longPress];
- (void)longPress:(UIGestureRecognizer *)longPress {
//获取点击在collectionView的坐标
CGPoint point=[longPress locationInView:self.collectionView];
//从长按开始
if (longPress.state == UIGestureRecognizerStateBegan) {
NSIndexPath *indexPath=[self.collectionView indexPathForItemAtPoint:point];
[self.collectionView beginInteractiveMovementForItemAtIndexPath:indexPath];
//长按手势状态改变
} else if(longPress.state==UIGestureRecognizerStateChanged) {
[self.collectionView updateInteractiveMovementTargetPosition:point];
//长按手势结束
} else if (longPress.state==UIGestureRecognizerStateEnded) {
[self.collectionView endInteractiveMovement];
//其他情况
} else {
[self.collectionView cancelInteractiveMovement];
}
}
- (NSIndexPath *)collectionView:(UICollectionView *)collectionView targetIndexPathForMoveFromItemAtIndexPath:(NSIndexPath *)originalIndexPath toProposedIndexPath:(NSIndexPath *)proposedIndexPath {
/* 两个indexpath参数, 分别代表源位置, 和将要移动的目的位置*/
//-1 是为了不让最后一个可以交换位置
if (proposedIndexPath.item == (_dataArrays.count - 1)) {
//初始位置
return originalIndexPath;
} else {
//-1 是为了不让最后一个可以交换位置
if (originalIndexPath.item == (_dataArrays.count - 1)) {
return originalIndexPath;
}
//      移动后的位置
return proposedIndexPath;
}
}
-(void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
//记录要移动的数据
id object= self.dataArrays[sourceIndexPath.item];
//删除要移动的数据
[self.dataArrays removeObjectAtIndex:sourceIndexPath.item];
//添加新的数据到指定的位置
[self.dataArrays insertObject:object atIndex:destinationIndexPath.item];
}

人已赞赏
iOS文章

IOS 3DTouch

2020-4-29 13:17:08

iOS文章

IOS动态获取键盘高度

2020-4-29 14:31:49

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
有新消息 消息中心
搜索