iOS - UICollectionView 長按拖拽單元格

一榄笙、先上gif效果圖,DEMO鏈接:https://gitee.com/xudongxiang/DragDropCollectionView.git

201812251450165.gif

二糊啡、代碼實現(xiàn)細(xì)節(jié)

1. 初始化collectionView堕扶,以及遵守UICollectionViewDelegate、UICollectionViewDataSource ,并且注冊cell等一波常規(guī)操作

UICollectionViewFlowLayout *collectionFlowLayout = [[UICollectionViewFlowLayout alloc] init];
collectionFlowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 375, 667) collectionViewLayout:collectionFlowLayout];
self.collectionView.backgroundColor = [UIColor whiteColor];
[self.collectionView registerClass:[CollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
self.collectionView.dataSource = self;
self.collectionView.delegate = self;
[self.view addSubview:self.collectionView];

2. 為collectionView添加長按手勢

// 添加長按抖動手勢
[self addRecognize];
- (void)addRecognize
{
    UILongPressGestureRecognizer *recognize = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressGestureAction:)];
    
    //設(shè)置長按響應(yīng)時間為0.5秒
    recognize.minimumPressDuration = 0.5;   
    
    [self.collectionView addGestureRecognizer:recognize];
}

3. 實現(xiàn)長按后collectionView的抖動效果匠抗,并且為collectionView添加拖動手勢

// 長按抖動手勢方法
- (void)longPressGestureAction:(UILongPressGestureRecognizer *)longGesture {
    switch (longGesture.state) {
        case UIGestureRecognizerStateBegan: {
        
            // 移除長按手勢
            [self.collectionView removeGestureRecognizer:longGesture];
            
            // 為collectionView添加拖動手勢
            [self addGesture];
            
             // 用一個BOOL類型的全局變量,記錄collectionView是否為抖動狀態(tài)门驾,YES:抖動,NO:停止抖動
            _isItemShake = YES; 
            [self.collectionView reloadData];
        }
            break;
        case UIGestureRecognizerStateChanged: {}
            break;
        case UIGestureRecognizerStateEnded: {}
            break;
        default:
            break;
    }
}
- (void)addGesture
{
    UILongPressGestureRecognizer *longGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handlelongGesture:)];
    longGesture.minimumPressDuration = 0;
    [self.collectionView addGestureRecognizer:longGesture];
}

4. 實現(xiàn)collectionView的拖動效果聂沙,下面會使用iOS9的新特性實現(xiàn)拖拽,必須調(diào)用UICollectionView的下面兩個方法

// 開始移動的時候調(diào)用此方法坷随,可以獲取相應(yīng)的datasource方法設(shè)置特殊的indexpath 能否移動,如果能移動返回的是YES ,不能移動返回的是NO
- (BOOL)beginInteractiveMovementForItemAtIndexPath:(NSIndexPath *)indexPath
// 更新移動過程的位置
- (void)updateInteractiveMovementTargetPosition:(CGPoint)targetPosition 
// 長按抖動手勢方法
- (void)handlelongGesture:(UILongPressGestureRecognizer *)longGesture {
    switch (longGesture.state) {
        case UIGestureRecognizerStateBegan:{
        
            // 通過手勢獲取點,通過點獲取點擊的indexPath, 移動該cell
            NSIndexPath *aIndexPath = [self.collectionView indexPathForItemAtPoint:[longGesture locationInView:self.collectionView]];
            [self.collectionView beginInteractiveMovementForItemAtIndexPath:aIndexPath];
            
        }
            break;
        case UIGestureRecognizerStateChanged:{
            
            // 通過手勢獲取點窃躲,通過點獲取拖動到的indexPath, 更新該cell位置
            [self.collectionView updateInteractiveMovementTargetPosition:[longGesture locationInView:self.collectionView]];
            
        }
            break;
        case UIGestureRecognizerStateEnded:{
        
            // 移動完成關(guān)閉cell移動
            [self.collectionView endInteractiveMovement];

        // 移除拖動手勢
            [self.collectionView removeGestureRecognizer:longGesture];

            // collectionView停止抖動
            _isItemShake = NO;
            
            // 為collectionView添加拖動手勢
            [self addRecognize];
            
            NSArray *cellArray = [self.collectionView visibleCells];
            for (CollectionViewCell *cell in cellArray ) {
                // 調(diào)用cell停止抖動方法
                [cell stopShake];
            }
        }
            break;
        default:
            [self.collectionView endInteractiveMovement];
            [self.collectionView removeGestureRecognizer:longGesture];
            _isItemShake = NO;
            [self addRecognize];
            NSArray *cellArray = [self.collectionView visibleCells];
            for (CollectionViewCell *cell in cellArray ) {
                [cell stopShake];
            }
            break;
    }
}

5. 實現(xiàn)UICollectionViewDelegate钦睡、UICollectionViewDataSource

- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
    // 刪除數(shù)據(jù)源中初始位置的數(shù)據(jù)
    id objc = [self.colorArray objectAtIndex:sourceIndexPath.item];
    [self.colorArray removeObject:objc];

    // 將數(shù)據(jù)插入數(shù)據(jù)源中新的位置蒂窒,實現(xiàn)數(shù)據(jù)源的更新
    [self.colorArray insertObject:objc atIndex:destinationIndexPath.item];
    
    NSArray *cellArray = [self.collectionView visibleCells];
    for (CollectionViewCell *cell in cellArray ) {
        [cell stopShake];
    }
}

//配置cell大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(167, 167);
}

//配置行間距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 15;
}

//配置每組上下左右的間距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 13, 15, 13);
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

//配置每個組里面有多少個cell
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.colorArray.count;
}
//配置cell,并且通過_isItemShake控制cell是否抖動
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    [cell loadWithModel:self.colorArray[indexPath.row] ];
    if (_isItemShake) {
    
    // 調(diào)用cell開始抖動方法
        [cell beginShake];
        
    }else{
    
        // 調(diào)用cell停止抖動方法
        [cell stopShake];
        
    }
    return cell;
}

6. 在CollectionViewCell.m文件中實現(xiàn)cell的抖動和停止抖動方法

// 實現(xiàn)cell抖動方法
- (void)beginShake
{
    CAKeyframeAnimation *anim = [CAKeyframeAnimation animation];
    anim.keyPath = @"transform.rotation";
    anim.duration = 0.2;
    anim.repeatCount = MAXFLOAT;
    anim.values = @[@(-0.03),@(0.03),@(-0.03)];
    anim.removedOnCompletion = NO;
    anim.fillMode = kCAFillModeForwards;
    [self.layer addAnimation:anim forKey:@"shake"];
}
// 實現(xiàn)cell停止抖動方法
- (void)stopShake
{
    [self.layer removeAllAnimations];
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市洒琢,隨后出現(xiàn)的幾起案子秧秉,更是在濱河造成了極大的恐慌,老刑警劉巖衰抑,帶你破解...
    沈念sama閱讀 218,858評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件象迎,死亡現(xiàn)場離奇詭異,居然都是意外死亡呛踊,警方通過查閱死者的電腦和手機砾淌,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,372評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來谭网,“玉大人汪厨,你說我怎么就攤上這事∮湓瘢” “怎么了劫乱?”我有些...
    開封第一講書人閱讀 165,282評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長锥涕。 經(jīng)常有香客問我衷戈,道長,這世上最難降的妖魔是什么站楚? 我笑而不...
    開封第一講書人閱讀 58,842評論 1 295
  • 正文 為了忘掉前任脱惰,我火速辦了婚禮搏嗡,結(jié)果婚禮上窿春,老公的妹妹穿的比我還像新娘。我一直安慰自己采盒,他們只是感情好旧乞,可當(dāng)我...
    茶點故事閱讀 67,857評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著磅氨,像睡著了一般尺栖。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上烦租,一...
    開封第一講書人閱讀 51,679評論 1 305
  • 那天延赌,我揣著相機與錄音,去河邊找鬼叉橱。 笑死挫以,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的窃祝。 我是一名探鬼主播掐松,決...
    沈念sama閱讀 40,406評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了大磺?” 一聲冷哼從身側(cè)響起抡句,我...
    開封第一講書人閱讀 39,311評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎杠愧,沒想到半個月后待榔,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,767評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡流济,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,945評論 3 336
  • 正文 我和宋清朗相戀三年究抓,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片袭灯。...
    茶點故事閱讀 40,090評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡刺下,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出稽荧,到底是詐尸還是另有隱情橘茉,我是刑警寧澤,帶...
    沈念sama閱讀 35,785評論 5 346
  • 正文 年R本政府宣布姨丈,位于F島的核電站畅卓,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏蟋恬。R本人自食惡果不足惜翁潘,卻給世界環(huán)境...
    茶點故事閱讀 41,420評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望歼争。 院中可真熱鬧拜马,春花似錦、人聲如沸沐绒。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,988評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽乔遮。三九已至扮超,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間蹋肮,已是汗流浹背出刷。 一陣腳步聲響...
    開封第一講書人閱讀 33,101評論 1 271
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留坯辩,地道東北人馁龟。 一個月前我還...
    沈念sama閱讀 48,298評論 3 372
  • 正文 我出身青樓,卻偏偏與公主長得像濒翻,于是被迫代替她去往敵國和親屁柏。 傳聞我的和親對象是個殘疾皇子啦膜,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,033評論 2 355

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