iOS collectionView拖拽排序

項目中首頁按鈕按照需求需要實現拖拽排序並且記錄排序後的佈局,下次再進入APP後展示排序後的佈局。

功能分析

實現此功能需要實現兩個點,第一就是拖拽排序的實現,第二就是存儲排序後的佈局,針對第一個功能點,拖拽排序:這個可以使用collectionView系統自帶的功能來實現,針對第二個功能點,我使用NSUserDefaults本地存儲盛放collectionViewCell內容的數組。
整體效果如圖:

本地存儲的實現

每個cell由背景圖片和title組成,NSDictionary *dic1 = @{@"title":@"標題", @"img":@"bgImg"};每個字典存放兩個字段,根據需求,創建相應的字典,NSArray *tempArr = @[dic1,dic2,dic3,dic4,dic5]``[self.homeBtnsArr addObjectsFromArray:tempArr];將字典放在數組中,便於在collectionView的代理方法中使用,[[NSUserDefaults standardUserDefaults] setObject:self.homeBtnsArr forKey:@"stuHomeBtns"];將數組做本地儲存,在每次進入界面時,先去NSUserDefaults中查找存放的數組,再去使用。

拖拽移動功能的實現

1、創建collectionView

UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake((SCREEN_WIDTH-50.0)/4, 85);
    flowLayout.minimumLineSpacing = 0.1;
    flowLayout.minimumInteritemSpacing = 0.1;
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
    collectionView.backgroundColor = [UIColor whiteColor];
    collectionView.delegate = self;
    collectionView.dataSource = self;
    self.collectionView = collectionView;
    [self addSubview:collectionView];
    [collectionView makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(0);
    }];
    [collectionView registerClass:[HomeSortBtnCell class] forCellWithReuseIdentifier:@"HomeSortBtnCell"];

2、在collectionView上添加長按手勢

UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handlelongGesture:)];
    [collectionView addGestureRecognizer:longPress];

3、長按手勢響應方法

#pragma mark 長按響應方法
- (void)handlelongGesture:(UILongPressGestureRecognizer *)longPress {
    [self action:longPress];
}

4、處理長按手勢

- (void)action:longPress:(UILongPressGestureRecognizer *)longPress {
    switch (longPress.state) {
        case UIGestureRecognizerStateBegan:
            {
                //手勢開始
                //判斷手勢落點位置是否在row上
                NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:[longPress locationInView:self.collectionView]];
                if (indexPath == nil) {
                    break;
                }
                HomeSortBtnCell *cell = (HomeSortBtnCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
                [self bringSubviewToFront:cell];
                //iOS9 方法 移動cell
                [self.collectionView beginInteractiveMovementForItemAtIndexPath:indexPath];
            }
            break;
        case UIGestureRecognizerStateChanged:
            {
                //iOS9 方法 移動過程中隨時更新cell位置
                [self.collectionView updateInteractiveMovementTargetPosition:[longPress locationInView:self.collectionView]];
            }
            break;
        case UIGestureRecognizerStateEnded:
            {
                //手勢結束
                //iOS9方法 移動結束後關閉cell移動
                [self.collectionView endInteractiveMovement];
            }
            break;
        default:
            [self.collectionView cancelInteractiveMovement];
            break;
    }
}

這裏處理長按手勢的時候,(一)、判斷手勢開始,判斷手勢落點位置是否在collectionView的cell上,collectionView系統的方法:indexPathForItemAtPoint:這裏的point爲:[longPress locationInView:self.collectionView],獲取到手勢落點的indexPath後,根據indexPath查找到相應位置的cell,然後[self bringSubviewToFront:cell];將cell提到前層展示,給人以懸浮的感覺,這時就開始了collectionView的移動操作:[self.collectionView beginInteractiveMovementForItemAtIndexPath:indexPath];。(二)、當手勢在移動的過程中,collectionView隨時更新cell的位置:[self.collectionView updateInteractiveMovementTargetPosition:[longPress locationInView:self.collectionView]];。(三)、手勢結束後,collectionView也隨之關閉cell的移動:[self.collectionView endInteractiveMovement];

這裏不僅僅需要處理手勢事件,還需要遵循collectionView相關的代理方法:

//開啓collectionView可以移動
- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
//處理collectionView移動過程中的數據操作
- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
    //取出移動row 數據
    NSDictionary *dic = self.viewModel.homeBtnsArr[sourceIndexPath.row];
    //從數據源中移除該數據
    [self.viewModel.homeBtnsArr removeObject:dic];
    //將數據插入到數據源中目標位置
    [self.viewModel.homeBtnsArr insertObject:dic atIndex:destinationIndexPath.row];
    
    NSArray *tempBtns = [self.viewModel.homeBtnsArr copy];
    if ([self.viewModel fetchIsTeacherRole]) {
        //教師端
        [[NSUserDefaults standardUserDefaults] setObject:tempBtns forKey:@"teaHomeBtns"];
    } else {
        [[NSUserDefaults standardUserDefaults] setObject:tempBtns forKey:@"stuHomeBtns"];
    }
}

- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath代理方法中,(一)、 //取出移動row 數據
NSDictionary dic = self.viewModel.homeBtnsArr[sourceIndexPath.row];(二)、//從數據源中移除該數據 [self.viewModel.homeBtnsArr removeObject:dic];(三)、//將數據插入到數據源中目標位置 [self.viewModel.homeBtnsArr insertObject:dic atIndex:destinationIndexPath.row];(四)、NSArray *tempBtns = [self.viewModel.homeBtnsArr copy];[[NSUserDefaults standardUserDefaults] setObject:tempBtns forKey:@"teaHomeBtns"];將改變後的cell內容數組存儲到本地。

以上就是iOS9及以上移動collectionViewCell的方法,我們利用系統封裝好的方法,相對比較容易的實現了功能。接下來看一下iOS9以下我們需要怎麼實現

iOS9以下
#pragma mark iOS9之前的方法
- (void)action:(UILongPressGestureRecognizer *)longPress {
    switch (longPress.state) {
        case UIGestureRecognizerStateBegan:
            {
                //手勢開始 判斷手勢落點位置是否在row上
                NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:[longPress locationInView:self.collectionView]];
                self.oldIndexPath = indexPath;
                if (indexPath == nil) {
                    break;
                }
                HomeSortBtnCell *cell = (HomeSortBtnCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
                //使用系統的截圖功能 得到cell的截圖視圖
                UIView *snapshotView = [cell snapshotViewAfterScreenUpdates:NO];
                snapshotView.frame = cell.frame;
                [self addSubview:self.snapShotView = snapshotView];
                //截圖後隱藏當前cell
                cell.hidden = YES;
                
                CGPoint currentPoint = [longPress locationInView:self.collectionView];
                [UIView animateWithDuration:0.25 animations:^{
                    snapshotView.transform = CGAffineTransformMakeScale(1.05, 1.05);
                    snapshotView.center = currentPoint;
                }];
                
                //取出移動row 數據
//                NSDictionary *dic = self.viewModel.homeBtnsArr[self.oldIndexPath.row];
//                //從數據源中移除該數據
//                [self.viewModel.homeBtnsArr removeObject:dic];
                
            }
            break;
        case UIGestureRecognizerStateChanged:
            {
                //手勢改變 當前手指位置 截圖視圖位置隨着手指移動而移動
                CGPoint currentPoint = [longPress locationInView:self.collectionView];
                self.snapShotView.center = currentPoint;
                //計算截圖視圖和哪個可見cell相交
                for (HomeSortBtnCell *cell in self.collectionView.visibleCells) {
                    //當前隱藏的cell就不需要交換了 直接continue
                    if ([self.collectionView indexPathForCell:cell] == self.oldIndexPath) {
                        continue;
                    }
                    //計算中心距
                    CGFloat space = sqrt(pow(self.snapShotView.center.x-cell.center.x, 2) + powf(self.snapShotView.center.y - cell.center.y, 2));
                    //如果相交一半就移動
                    if (space <= self.snapShotView.bounds.size.width/2) {
                        self.moveIndexPath = [self.collectionView indexPathForCell:cell];
                       /*更新數據源 須在移動之前*/
                        //取出移動row 數據
                        NSDictionary *dic = self.viewModel.homeBtnsArr[self.oldIndexPath.row];
                        //從數據源中移除該數據
                        [self.viewModel.homeBtnsArr removeObject:dic];
                        //將數據插入到數據源中目標位置
                        [self.viewModel.homeBtnsArr insertObject:dic atIndex:self.moveIndexPath.row];
                        
                        //移動 會調用MoveToIndexPath方法更新數據源
                        [self.collectionView moveItemAtIndexPath:self.oldIndexPath toIndexPath:self.moveIndexPath];
                        
                        //設置移動後的起始indexPath
                        self.oldIndexPath = self.moveIndexPath;
                        break;
                    }
                }
            }
            break;
        default:
            {
             //手勢結束和其他狀態
                HomeSortBtnCell *cell = (HomeSortBtnCell *)[self.collectionView cellForItemAtIndexPath:self.oldIndexPath];
                //結束動畫過程中停止交互,防止出問題
                self.collectionView.userInteractionEnabled = NO;
                //給截圖視圖一個動畫移動到隱藏cell的新位置
                [UIView animateWithDuration:0.25 animations:^{
                    self.snapShotView.center = cell.center;
                    self.snapShotView.transform = CGAffineTransformMakeScale(1.0, 1.0);
                } completion:^(BOOL finished) {
                    //移除截圖視圖,顯示隱藏的cell並開始交互
                    [self.snapShotView removeFromSuperview];
                    cell.hidden = NO;
                    self.collectionView.userInteractionEnabled = YES;
                    
                    //本地存儲已修改的按鈕數組
                    NSArray *tempBtns = [self.viewModel.homeBtnsArr copy];
                    if ([self.viewModel fetchIsTeacherRole]) {
                        //教師端
                        [[NSUserDefaults standardUserDefaults] setObject:tempBtns forKey:@"teaHomeBtns"];
                    } else {
                        [[NSUserDefaults standardUserDefaults] setObject:tempBtns forKey:@"stuHomeBtns"];
                    }
                }];
            }
            break;
    }
}

iOS9以下就相對 麻煩些了,首先在手勢開始時,我們也同樣需要找到手勢落點所在位置的cell,然後使用系統的截圖功能,得到cell的截圖視圖
UIView *snapshotView = [cell snapshotViewAfterScreenUpdates:NO]; snapshotView.frame = cell.frame; [self addSubview:self.snapShotView = snapshotView]; //截圖後隱藏當前cell cell.hidden = YES; CGPoint currentPoint = [longPress locationInView:self.collectionView]; [UIView animateWithDuration:0.25 animations:^{ snapshotView.transform = CGAffineTransformMakeScale(1.05, 1.05); snapshotView.center = currentPoint; }];
這裏我們做這麼多的操作,在iOS9及以上我們相應做的操作是:[self bringSubviewToFront:cell]; //iOS9 方法 移動cell [self.collectionView beginInteractiveMovementForItemAtIndexPath:indexPath];。當手勢發生改變,也就是我們開始移動的時候,截圖的視圖位置也隨着手指移動而移動CGPoint currentPoint = [longPress locationInView:self.collectionView]; self.snapShotView.center = currentPoint;我們需要自己計算截圖視圖和哪個可見cell相交:for (HomeSortBtnCell *cell in self.collectionView.visibleCells) { //當前隱藏的cell就不需要交換了 直接continue if ([self.collectionView indexPathForCell:cell] == self.oldIndexPath) { continue; } //計算中心距 CGFloat space = sqrt(pow(self.snapShotView.center.x-cell.center.x, 2) + powf(self.snapShotView.center.y - cell.center.y, 2)); //如果相交一半就移動 if (space <= self.snapShotView.bounds.size.width/2) { self.moveIndexPath = [self.collectionView indexPathForCell:cell]; /*更新數據源 須在移動之前*/ //取出移動row 數據 NSDictionary *dic = self.viewModel.homeBtnsArr[self.oldIndexPath.row]; //從數據源中移除該數據 [self.viewModel.homeBtnsArr removeObject:dic]; //將數據插入到數據源中目標位置 [self.viewModel.homeBtnsArr insertObject:dic atIndex:self.moveIndexPath.row]; //移動 會調用MoveToIndexPath方法更新數據源 [self.collectionView moveItemAtIndexPath:self.oldIndexPath toIndexPath:self.moveIndexPath]; //設置移動後的起始indexPath self.oldIndexPath = self.moveIndexPath; break; } }
手勢結束之後,我們需要將截圖的視圖隱藏移除,並且刷新當前視圖佈局:
//手勢結束和其他狀態 HomeSortBtnCell *cell = (HomeSortBtnCell *)[self.collectionView cellForItemAtIndexPath:self.oldIndexPath]; //結束動畫過程中停止交互,防止出問題 self.collectionView.userInteractionEnabled = NO; //給截圖視圖一個動畫移動到隱藏cell的新位置 [UIView animateWithDuration:0.25 animations:^{ self.snapShotView.center = cell.center; self.snapShotView.transform = CGAffineTransformMakeScale(1.0, 1.0); } completion:^(BOOL finished) { //移除截圖視圖,顯示隱藏的cell並開始交互 [self.snapShotView removeFromSuperview]; cell.hidden = NO; self.collectionView.userInteractionEnabled = YES; //本地存儲已修改的按鈕數組 NSArray *tempBtns = [self.viewModel.homeBtnsArr copy]; if ([self.viewModel fetchIsTeacherRole]) { //教師端 [[NSUserDefaults standardUserDefaults] setObject:tempBtns forKey:@"teaHomeBtns"]; } else { [[NSUserDefaults standardUserDefaults] setObject:tempBtns forKey:@"stuHomeBtns"]; } }];

上述就是實現這個功能的基本流程了。ps iOS9以下的設備已經較少了,我們現在大多使用第一種方法了,相比較而言還是有優勢的。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章