iOS collectionView拖拽排序

項(xiàng)目中首頁按鈕按照需求需要實(shí)現(xiàn)拖拽排序并且記錄排序后的布局冗懦,下次再進(jìn)入APP后展示排序后的布局。

功能分析

實(shí)現(xiàn)此功能需要實(shí)現(xiàn)兩個(gè)點(diǎn)仇祭,第一就是拖拽排序的實(shí)現(xiàn)披蕉,第二就是存儲(chǔ)排序后的布局,針對(duì)第一個(gè)功能點(diǎn)乌奇,拖拽排序:這個(gè)可以使用collectionView系統(tǒng)自帶的功能來實(shí)現(xiàn)没讲,針對(duì)第二個(gè)功能點(diǎn),我使用NSUserDefaults本地存儲(chǔ)盛放collectionViewCell內(nèi)容的數(shù)組礁苗。
整體效果如圖:

屏幕快照 2019-01-29 上午11.10.24.png

本地存儲(chǔ)的實(shí)現(xiàn)

每個(gè)cell由背景圖片和title組成爬凑,NSDictionary *dic1 = @{@"title":@"標(biāo)題", @"img":@"bgImg"};每個(gè)字典存放兩個(gè)字段,根據(jù)需求试伙,創(chuàng)建相應(yīng)的字典嘁信,NSArray *tempArr = @[dic1,dic2,dic3,dic4,dic5]``[self.homeBtnsArr addObjectsFromArray:tempArr];將字典放在數(shù)組中,便于在collectionView的代理方法中使用疏叨,[[NSUserDefaults standardUserDefaults] setObject:self.homeBtnsArr forKey:@"stuHomeBtns"];將數(shù)組做本地儲(chǔ)存潘靖,在每次進(jìn)入界面時(shí),先去NSUserDefaults中查找存放的數(shù)組蚤蔓,再去使用卦溢。

拖拽移動(dòng)功能的實(shí)現(xiàn)

1、創(chuàng)建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单寂、長按手勢響應(yīng)方法

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

4、處理長按手勢

- (void)action:longPress:(UILongPressGestureRecognizer *)longPress {
    switch (longPress.state) {
        case UIGestureRecognizerStateBegan:
            {
                //手勢開始
                //判斷手勢落點(diǎn)位置是否在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 方法 移動(dòng)cell
                [self.collectionView beginInteractiveMovementForItemAtIndexPath:indexPath];
            }
            break;
        case UIGestureRecognizerStateChanged:
            {
                //iOS9 方法 移動(dòng)過程中隨時(shí)更新cell位置
                [self.collectionView updateInteractiveMovementTargetPosition:[longPress locationInView:self.collectionView]];
            }
            break;
        case UIGestureRecognizerStateEnded:
            {
                //手勢結(jié)束
                //iOS9方法 移動(dòng)結(jié)束后關(guān)閉cell移動(dòng)
                [self.collectionView endInteractiveMovement];
            }
            break;
        default:
            [self.collectionView cancelInteractiveMovement];
            break;
    }
}

這里處理長按手勢的時(shí)候涮坐,(一)凄贩、判斷手勢開始誓军,判斷手勢落點(diǎn)位置是否在collectionView的cell上袱讹,collectionView系統(tǒng)的方法:indexPathForItemAtPoint:這里的point為:[longPress locationInView:self.collectionView],獲取到手勢落點(diǎn)的indexPath后昵时,根據(jù)indexPath查找到相應(yīng)位置的cell捷雕,然后[self bringSubviewToFront:cell];將cell提到前層展示,給人以懸浮的感覺壹甥,這時(shí)就開始了collectionView的移動(dòng)操作:[self.collectionView beginInteractiveMovementForItemAtIndexPath:indexPath];救巷。(二)、當(dāng)手勢在移動(dòng)的過程中句柠,collectionView隨時(shí)更新cell的位置:[self.collectionView updateInteractiveMovementTargetPosition:[longPress locationInView:self.collectionView]];浦译。(三)棒假、手勢結(jié)束后,collectionView也隨之關(guān)閉cell的移動(dòng):[self.collectionView endInteractiveMovement];精盅。

這里不僅僅需要處理手勢事件帽哑,還需要遵循collectionView相關(guān)的代理方法:

//開啟collectionView可以移動(dòng)
- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
//處理collectionView移動(dòng)過程中的數(shù)據(jù)操作
- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
    //取出移動(dòng)row 數(shù)據(jù)
    NSDictionary *dic = self.viewModel.homeBtnsArr[sourceIndexPath.row];
    //從數(shù)據(jù)源中移除該數(shù)據(jù)
    [self.viewModel.homeBtnsArr removeObject:dic];
    //將數(shù)據(jù)插入到數(shù)據(jù)源中目標(biāo)位置
    [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代理方法中,(一)叹俏、 //取出移動(dòng)row 數(shù)據(jù)
NSDictionary dic = self.viewModel.homeBtnsArr[sourceIndexPath.row];(二)妻枕、//從數(shù)據(jù)源中移除該數(shù)據(jù) [self.viewModel.homeBtnsArr removeObject:dic];(三)、//將數(shù)據(jù)插入到數(shù)據(jù)源中目標(biāo)位置 [self.viewModel.homeBtnsArr insertObject:dic atIndex:destinationIndexPath.row];(四)粘驰、NSArray *tempBtns = [self.viewModel.homeBtnsArr copy];[[NSUserDefaults standardUserDefaults] setObject:tempBtns forKey:@"teaHomeBtns"];將改變后的cell內(nèi)容數(shù)組存儲(chǔ)到本地屡谐。

以上就是iOS9及以上移動(dòng)collectionViewCell的方法,我們利用系統(tǒng)封裝好的方法蝌数,相對(duì)比較容易的實(shí)現(xiàn)了功能愕掏。接下來看一下iOS9以下我們需要怎么實(shí)現(xiàn)

iOS9以下
#pragma mark iOS9之前的方法
- (void)action:(UILongPressGestureRecognizer *)longPress {
    switch (longPress.state) {
        case UIGestureRecognizerStateBegan:
            {
                //手勢開始 判斷手勢落點(diǎn)位置是否在row上
                NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:[longPress locationInView:self.collectionView]];
                self.oldIndexPath = indexPath;
                if (indexPath == nil) {
                    break;
                }
                HomeSortBtnCell *cell = (HomeSortBtnCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
                //使用系統(tǒng)的截圖功能 得到cell的截圖視圖
                UIView *snapshotView = [cell snapshotViewAfterScreenUpdates:NO];
                snapshotView.frame = cell.frame;
                [self addSubview:self.snapShotView = snapshotView];
                //截圖后隱藏當(dāng)前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;
                }];
                
                //取出移動(dòng)row 數(shù)據(jù)
//                NSDictionary *dic = self.viewModel.homeBtnsArr[self.oldIndexPath.row];
//                //從數(shù)據(jù)源中移除該數(shù)據(jù)
//                [self.viewModel.homeBtnsArr removeObject:dic];
                
            }
            break;
        case UIGestureRecognizerStateChanged:
            {
                //手勢改變 當(dāng)前手指位置 截圖視圖位置隨著手指移動(dòng)而移動(dòng)
                CGPoint currentPoint = [longPress locationInView:self.collectionView];
                self.snapShotView.center = currentPoint;
                //計(jì)算截圖視圖和哪個(gè)可見cell相交
                for (HomeSortBtnCell *cell in self.collectionView.visibleCells) {
                    //當(dāng)前隱藏的cell就不需要交換了 直接continue
                    if ([self.collectionView indexPathForCell:cell] == self.oldIndexPath) {
                        continue;
                    }
                    //計(jì)算中心距
                    CGFloat space = sqrt(pow(self.snapShotView.center.x-cell.center.x, 2) + powf(self.snapShotView.center.y - cell.center.y, 2));
                    //如果相交一半就移動(dòng)
                    if (space <= self.snapShotView.bounds.size.width/2) {
                        self.moveIndexPath = [self.collectionView indexPathForCell:cell];
                       /*更新數(shù)據(jù)源 須在移動(dòng)之前*/
                        //取出移動(dòng)row 數(shù)據(jù)
                        NSDictionary *dic = self.viewModel.homeBtnsArr[self.oldIndexPath.row];
                        //從數(shù)據(jù)源中移除該數(shù)據(jù)
                        [self.viewModel.homeBtnsArr removeObject:dic];
                        //將數(shù)據(jù)插入到數(shù)據(jù)源中目標(biāo)位置
                        [self.viewModel.homeBtnsArr insertObject:dic atIndex:self.moveIndexPath.row];
                        
                        //移動(dòng) 會(huì)調(diào)用MoveToIndexPath方法更新數(shù)據(jù)源
                        [self.collectionView moveItemAtIndexPath:self.oldIndexPath toIndexPath:self.moveIndexPath];
                        
                        //設(shè)置移動(dòng)后的起始indexPath
                        self.oldIndexPath = self.moveIndexPath;
                        break;
                    }
                }
            }
            break;
        default:
            {
             //手勢結(jié)束和其他狀態(tài)
                HomeSortBtnCell *cell = (HomeSortBtnCell *)[self.collectionView cellForItemAtIndexPath:self.oldIndexPath];
                //結(jié)束動(dòng)畫過程中停止交互,防止出問題
                self.collectionView.userInteractionEnabled = NO;
                //給截圖視圖一個(gè)動(dòng)畫移動(dòng)到隱藏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;
                    
                    //本地存儲(chǔ)已修改的按鈕數(shù)組
                    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以下就相對(duì) 麻煩些了亭珍,首先在手勢開始時(shí),我們也同樣需要找到手勢落點(diǎn)所在位置的cell枝哄,然后使用系統(tǒng)的截圖功能肄梨,得到cell的截圖視圖
UIView *snapshotView = [cell snapshotViewAfterScreenUpdates:NO]; snapshotView.frame = cell.frame; [self addSubview:self.snapShotView = snapshotView]; //截圖后隱藏當(dāng)前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及以上我們相應(yīng)做的操作是:[self bringSubviewToFront:cell]; //iOS9 方法 移動(dòng)cell [self.collectionView beginInteractiveMovementForItemAtIndexPath:indexPath];挠锥。當(dāng)手勢發(fā)生改變众羡,也就是我們開始移動(dòng)的時(shí)候,截圖的視圖位置也隨著手指移動(dòng)而移動(dòng)CGPoint currentPoint = [longPress locationInView:self.collectionView]; self.snapShotView.center = currentPoint;我們需要自己計(jì)算截圖視圖和哪個(gè)可見cell相交:for (HomeSortBtnCell *cell in self.collectionView.visibleCells) { //當(dāng)前隱藏的cell就不需要交換了 直接continue if ([self.collectionView indexPathForCell:cell] == self.oldIndexPath) { continue; } //計(jì)算中心距 CGFloat space = sqrt(pow(self.snapShotView.center.x-cell.center.x, 2) + powf(self.snapShotView.center.y - cell.center.y, 2)); //如果相交一半就移動(dòng) if (space <= self.snapShotView.bounds.size.width/2) { self.moveIndexPath = [self.collectionView indexPathForCell:cell]; /*更新數(shù)據(jù)源 須在移動(dòng)之前*/ //取出移動(dòng)row 數(shù)據(jù) NSDictionary *dic = self.viewModel.homeBtnsArr[self.oldIndexPath.row]; //從數(shù)據(jù)源中移除該數(shù)據(jù) [self.viewModel.homeBtnsArr removeObject:dic]; //將數(shù)據(jù)插入到數(shù)據(jù)源中目標(biāo)位置 [self.viewModel.homeBtnsArr insertObject:dic atIndex:self.moveIndexPath.row]; //移動(dòng) 會(huì)調(diào)用MoveToIndexPath方法更新數(shù)據(jù)源 [self.collectionView moveItemAtIndexPath:self.oldIndexPath toIndexPath:self.moveIndexPath]; //設(shè)置移動(dòng)后的起始indexPath self.oldIndexPath = self.moveIndexPath; break; } }
手勢結(jié)束之后蓖租,我們需要將截圖的視圖隱藏移除粱侣,并且刷新當(dāng)前視圖布局:
//手勢結(jié)束和其他狀態(tài) HomeSortBtnCell *cell = (HomeSortBtnCell *)[self.collectionView cellForItemAtIndexPath:self.oldIndexPath]; //結(jié)束動(dòng)畫過程中停止交互,防止出問題 self.collectionView.userInteractionEnabled = NO; //給截圖視圖一個(gè)動(dòng)畫移動(dòng)到隱藏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; //本地存儲(chǔ)已修改的按鈕數(shù)組 NSArray *tempBtns = [self.viewModel.homeBtnsArr copy]; if ([self.viewModel fetchIsTeacherRole]) { //教師端 [[NSUserDefaults standardUserDefaults] setObject:tempBtns forKey:@"teaHomeBtns"]; } else { [[NSUserDefaults standardUserDefaults] setObject:tempBtns forKey:@"stuHomeBtns"]; } }];

上述就是實(shí)現(xiàn)這個(gè)功能的基本流程了齐婴。ps iOS9以下的設(shè)備已經(jīng)較少了,我們現(xiàn)在大多使用第一種方法了稠茂,相比較而言還是有優(yōu)勢的柠偶。
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市睬关,隨后出現(xiàn)的幾起案子诱担,更是在濱河造成了極大的恐慌,老刑警劉巖电爹,帶你破解...
    沈念sama閱讀 217,734評(píng)論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件蔫仙,死亡現(xiàn)場離奇詭異,居然都是意外死亡丐箩,警方通過查閱死者的電腦和手機(jī)摇邦,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,931評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門恤煞,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人施籍,你說我怎么就攤上這事阱州。” “怎么了法梯?”我有些...
    開封第一講書人閱讀 164,133評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵苔货,是天一觀的道長。 經(jīng)常有香客問我立哑,道長夜惭,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,532評(píng)論 1 293
  • 正文 為了忘掉前任铛绰,我火速辦了婚禮诈茧,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘捂掰。我一直安慰自己敢会,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,585評(píng)論 6 392
  • 文/花漫 我一把揭開白布这嚣。 她就那樣靜靜地躺著鸥昏,像睡著了一般。 火紅的嫁衣襯著肌膚如雪姐帚。 梳的紋絲不亂的頭發(fā)上吏垮,一...
    開封第一講書人閱讀 51,462評(píng)論 1 302
  • 那天,我揣著相機(jī)與錄音罐旗,去河邊找鬼膳汪。 笑死,一個(gè)胖子當(dāng)著我的面吹牛九秀,可吹牛的內(nèi)容都是我干的遗嗽。 我是一名探鬼主播,決...
    沈念sama閱讀 40,262評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼鼓蜒,長吁一口氣:“原來是場噩夢啊……” “哼痹换!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起友酱,我...
    開封第一講書人閱讀 39,153評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤晴音,失蹤者是張志新(化名)和其女友劉穎柔纵,沒想到半個(gè)月后缔杉,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,587評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡搁料,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,792評(píng)論 3 336
  • 正文 我和宋清朗相戀三年或详,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了系羞。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,919評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡霸琴,死狀恐怖椒振,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情梧乘,我是刑警寧澤澎迎,帶...
    沈念sama閱讀 35,635評(píng)論 5 345
  • 正文 年R本政府宣布,位于F島的核電站选调,受9級(jí)特大地震影響夹供,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜仁堪,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,237評(píng)論 3 329
  • 文/蒙蒙 一哮洽、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧弦聂,春花似錦鸟辅、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,855評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至捺檬,卻和暖如春洒缀,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背欺冀。 一陣腳步聲響...
    開封第一講書人閱讀 32,983評(píng)論 1 269
  • 我被黑心中介騙來泰國打工树绩, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人隐轩。 一個(gè)月前我還...
    沈念sama閱讀 48,048評(píng)論 3 370
  • 正文 我出身青樓饺饭,卻偏偏與公主長得像,于是被迫代替她去往敵國和親职车。 傳聞我的和親對(duì)象是個(gè)殘疾皇子瘫俊,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,864評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容