collectionView在iOS9中發佈了一個能夠移動cell的新特性,實現以下:ios
1.建立collectionView並設置代理數組
- (UICollectionView *)collectionView{ if (_collectionView == nil) { UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init]; layout.itemSize = CGSizeMake(50, 50); _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 20, self.view.bounds.size.width, self.view.bounds.size.height) collectionViewLayout:layout]; layout.minimumLineSpacing = 10; layout.minimumInteritemSpacing = 10; [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"Cell"]; _collectionView.backgroundColor = [UIColor cyanColor]; _collectionView.dataSource = self; //此處給其增長長按手勢,用此手勢觸發cell移動效果 UILongPressGestureRecognizer *longGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handlelongGesture:)]; [_collectionView addGestureRecognizer:longGesture]; } return _collectionView; }
2.設置其資源ui
_dataSource = [NSMutableArray array]; for (int i = 1; i <= 50; i++) { NSString *imageName = [NSString stringWithFormat:@"%d",i]; [_dataSource addObject:imageName]; }
3.監聽手勢,並設置其容許移動cell和交換資源spa
- (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]; break; default: [self.collectionView cancelInteractiveMovement]; break; } } - (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath{ //返回YES容許其item移動 return YES; } - (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath*)destinationIndexPath { //取出源item數據 id objc = [_dataSource objectAtIndex:sourceIndexPath.item]; //從資源數組中移除該數據 [_dataSource removeObject:objc]; //將數據插入到資源數組中的目標位置上 [_dataSource insertObject:objc atIndex:destinationIndexPath.item]; }
原文連接:iOS9 UICollectionView拖拽移動單元格代理
阿斯頓撒 code