一.效果圖
二.核心方法
1.在iOS 9之后系統提供了一套API用於實現重排
// Support for reordering
- (BOOL)beginInteractiveMovementForItemAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(9_0); // returns NO if reordering was prevented from beginning - otherwise YES
- (void)updateInteractiveMovementTargetPosition:(CGPoint)targetPosition NS_AVAILABLE_IOS(9_0);
- (void)endInteractiveMovement NS_AVAILABLE_IOS(9_0);
- (void)cancelInteractiveMovement NS_AVAILABLE_IOS(9_0);
2.這里采用給UICollectionView添加長按手勢
,結合系統API實現拖拽重排
- 給collectionView添加長按手勢
#pragma mark - 添加長按手勢
- (void)setUpLongPressGes {
UILongPressGestureRecognizer *longPresssGes = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressMethod:)];
[self.collectionView addGestureRecognizer:longPresssGes];
}
- 監聽長按手勢,根據長按手勢狀態實現collectionView的重排方法
- (void)longPressMethod:(UILongPressGestureRecognizer *)longPressGes {
// 判斷手勢狀態
switch (longPressGes.state) {
case UIGestureRecognizerStateBegan: {
// 判斷手勢落點位置是否在路徑上(長按cell時,顯示對應cell的位置,如path = 1 - 0,即表示長按的是第1組第0個cell). 點擊除了cell的其他地方皆顯示為null
NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:[longPressGes locationInView:self.collectionView]];
// 如果點擊的位置不是cell,break
if (nil == indexPath) {
break;
}
NSLog(@"%@",indexPath);
// 在路徑上則開始移動該路徑上的cell
[self.collectionView beginInteractiveMovementForItemAtIndexPath:indexPath];
}
break;
case UIGestureRecognizerStateChanged:
// 移動過程當中隨時更新cell位置
[self.collectionView updateInteractiveMovementTargetPosition:[longPressGes locationInView:self.collectionView]];
break;
case UIGestureRecognizerStateEnded:
// 移動結束后關閉cell移動
[self.collectionView endInteractiveMovement];
break;
default:
[self.collectionView cancelInteractiveMovement];
break;
}
}
- 實現這個方法才能移動cell
- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
// 取出來源組
ClassifyItem *sourceItem = self.classifyArray[sourceIndexPath.section];
// 取出item數據
ClassifyDetailItem *detailItem = [sourceItem.tags objectAtIndex:sourceIndexPath.row];
// 從資源數組中移除該數據
[sourceItem.tags removeObject:detailItem];
// 取出目標組
ClassifyItem *destinationItem = self.classifyArray[destinationIndexPath.section];
// 將數據插入到資源數組中的目標位置上
[destinationItem.tags insertObject:detailItem atIndex:destinationIndexPath.row];
}