iOS UICollectionViewCell拖拽移動(配Demo下載)

iOS拖拽移動UICollectionView下載地址:http://download.csdn.net/detail/lovechris00/9587439

 

這個月項目用到了拖拽移動UICollectionView的位置,

實現效果:

       

 

 

原理如下:

 

 

 

拖拽方法

1、獲取當前手勢位置,及對應cell的indexPath

 

- (void)longPressGestureRecognized:(id)sender{

    UILongPressGestureRecognizer *longPress = (UILongPressGestureRecognizer *)sender;
    UIGestureRecognizerState longPressState = longPress.state;
    //手指在collectionView中的位置
    _fingerLocation = [longPress locationInView:self];
    //手指按住位置對應的indexPath,可能爲nil
    _relocatedIndexPath = [self indexPathForItemAtPoint:_fingerLocation];

 

 

 

 

 

開始拖拽

1、設置開始時選中的Cell的位置(indexPath)爲初始位置;

 

 //手勢開始,對被選中cell截圖,隱藏原cell
            _originalIndexPath = [self indexPathForItemAtPoint:_fingerLocation];
            

 

 

 

2、對被選中cell截圖,隱藏原cell

originalIndexPath可能爲空,需要非空判斷

 

if (_originalIndexPath) {
                 [self cellSelectedAtIndexPath:_originalIndexPath];
            }

 

 

 

 

/**
 *  cell被長按手指選中,對其進行截圖,原cell隱藏
 */
- (void)cellSelectedAtIndexPath:(NSIndexPath *)indexPath{
  
    UICollectionViewCell *cell = [self cellForItemAtIndexPath:indexPath] ;
    
    UIView *snapshot = [self customSnapshotFromView:cell];
    
    [self addSubview:snapshot];
    
    _snapshot = snapshot;
    cell.hidden = YES;
    CGPoint center = _snapshot.center;
    center.y = _fingerLocation.y;
    [UIView animateWithDuration:0.2 animations:^{
        _snapshot.transform = CGAffineTransformMakeScale(1.03, 1.03);
        _snapshot.alpha = 0.98;
        _snapshot.center = center;
    }];
}

 

 

 

 

 

 

#pragma mark - 返回一個給定view的截圖.
- (UIView *)customSnapshotFromView:(UIView *)inputView {
    
    // Make an image from the input view.
    UIGraphicsBeginImageContextWithOptions(inputView.bounds.size, NO, 0);
    [inputView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    // Create an image view.
    UIView *snapshot = [[UIImageView alloc] initWithImage:image];
    snapshot.center = inputView.center;
    snapshot.layer.masksToBounds = NO;
    snapshot.layer.cornerRadius = 0.0;
    snapshot.layer.shadowOffset = CGSizeMake(-5.0, 0.0);
    snapshot.layer.shadowRadius = 5.0;
    snapshot.layer.shadowOpacity = 0.4;
    
    return snapshot;
}

 

 

 

 

 

拖拽過程中

1、截圖跟隨手指移動

 

 //截圖跟隨手指移動
            CGPoint center = _snapshot.center;
            center.y = _fingerLocation.y;
            center.x = _fingerLocation.x ;
            _snapshot.center = center;

 

 

 

2、判斷是否到達整個collectionView的邊緣

如果到了邊緣,就

 

判斷邏輯,該截圖的最小Y大於collectionView的最大Y ,就向上滾動

最大Y值小於collectionView的最小Y,就向下滾動

 

 

 

 if ([self checkIfSnapshotMeetsEdge]) {
                    [self startAutoScrollTimer];
                }else{
                    [self stopAutoScrollTimer];
                }

 

 

#pragma mark -  檢查截圖是否到達整個collectionView的邊緣,並作出響應

- (BOOL)checkIfSnapshotMeetsEdge{
    CGFloat minY = CGRectGetMinY(_snapshot.frame);
    CGFloat maxY = CGRectGetMaxY(_snapshot.frame);
    if (minY < self.contentOffset.y) {
        _autoScrollDirection = RTSnapshotMeetsEdgeTop;
        return YES;
    }
    if (maxY > self.bounds.size.height + self.contentOffset.y) {
        _autoScrollDirection = RTSnapshotMeetsEdgeBottom;
        return YES;
    }
    return NO;
}

 

#pragma mark - timer methods
/**
 *  創建定時器並運行
 */
- (void)startAutoScrollTimer{
    if (!_autoScrollTimer) {
        _autoScrollTimer = [CADisplayLink displayLinkWithTarget:self selector:@selector(startAutoScroll)];
        [_autoScrollTimer addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
    }
}
/**
 *  停止定時器並銷燬
 */
- (void)stopAutoScrollTimer{
    if (_autoScrollTimer) {
        [_autoScrollTimer invalidate];
        _autoScrollTimer = nil;
    }
}

 

 

 

 

#pragma mark - 開始自動滾動

- (void)startAutoScroll{
    CGFloat pixelSpeed = 4;
    if (_autoScrollDirection == RTSnapshotMeetsEdgeTop) {//向下滾動
        if (self.contentOffset.y > 0) {//向下滾動最大範圍限制
            [self setContentOffset:CGPointMake(0, self.contentOffset.y - pixelSpeed)];
            _snapshot.center = CGPointMake(_snapshot.center.x, _snapshot.center.y - pixelSpeed);
        }
    }else{                                               //向上滾動
        if (self.contentOffset.y + self.bounds.size.height < self.contentSize.height) {//向下滾動最大範圍限制
            [self setContentOffset:CGPointMake(0, self.contentOffset.y + pixelSpeed)];
            _snapshot.center = CGPointMake(_snapshot.center.x, _snapshot.center.y + pixelSpeed);
        }
    }
    
    /*  當把截圖拖動到邊緣,開始自動滾動,如果這時手指完全不動,則不會觸發‘UIGestureRecognizerStateChanged’,對應的代碼就不會執行,導致雖然截圖在tableView中的位置變了,但並沒有移動那個隱藏的cell,用下面代碼可解決此問題,cell會隨着截圖的移動而移動
     */
//    _relocatedIndexPath = [self indexPathForRowAtPoint:_snapshot.center];
    _relocatedIndexPath = [self indexPathForItemAtPoint:_snapshot.center] ;
    if (_relocatedIndexPath && ![_relocatedIndexPath isEqual:_originalIndexPath]) {
        [self cellRelocatedToNewIndexPath:_relocatedIndexPath];
    }
}

 

 

 

3、判斷是否進入其他cell的範圍

 

 

  if (_relocatedIndexPath && ![_relocatedIndexPath isEqual:_originalIndexPath]) {
                [self cellRelocatedToNewIndexPath:_relocatedIndexPath];
                NSLog(@"elocated Success");
            }

 

 

 

如果到達了

 

1)就獲取數據並更新數據源

2)把當前手勢的位置作爲初始位置;

3)把數據通過代理傳出去;

 

 

- (void)cellRelocatedToNewIndexPath:(NSIndexPath *)indexPath{
    //更新數據源並返回給外部
    [self updateDataSource];
    //交換移動cell位置
   
    [self moveItemAtIndexPath:_originalIndexPath toIndexPath:indexPath];
   //更新cell的原始indexPath爲當前indexPath
   _originalIndexPath = indexPath;

}

 

 

 

 

 

 

 

 

# pragma mark - Private methods
/**修改數據源,通知外部更新數據源*/
- (void)updateDataSource{
    
    //通過DataSource代理獲得原始數據源數組
    NSMutableArray *tempArray = [NSMutableArray array];
    if ([self.adataSource respondsToSelector:@selector(originalArrayDataForcollectionView:)]) {
        [tempArray addObjectsFromArray:[self.adataSource originalArrayDataForcollectionView:self]];
    }
    
    //移動數據
    [self moveObjectInMutableArray:tempArray fromIndex:_originalIndexPath.row toIndex:_relocatedIndexPath.row];
    
    //    將新數組傳出外部以更改數據源
    if ([self.adelegate respondsToSelector:@selector(collectionView:newArrayDataForDataSource:)]) {
        [self.adelegate collectionView:self newArrayDataForDataSource:tempArray];
    }
}

 

 

 

 

 

 

/**
 *  將可變數組中的一個對象移動到該數組中的另外一個位置
 *  @param array     要變動的數組
 *  @param fromIndex 從這個index
 *  @param toIndex   移至這個index
 */
- (void)moveObjectInMutableArray:(NSMutableArray *)array fromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex{
    
    NSInteger tempIndex = 0;
    NSMutableString *tempTitle = nil;
    
    if (fromIndex < toIndex) {
        for (NSInteger i = fromIndex; i < toIndex; i ++) {
            [array exchangeObjectAtIndex:i withObjectAtIndex:i + 1];
        }
    }else{
        for (NSInteger i = fromIndex; i > toIndex; i --) {
            [array exchangeObjectAtIndex:i withObjectAtIndex:i - 1];
        }
    }
}

 

 

 

 

 

拖拽結束

1、停止動畫;

 

 [self stopAutoScrollTimer];
            [self didEndDraging];
            if ([self.adelegate respondsToSelector:@selector(cellDidEndMovingIncollectionView:)]) {
                [self.adelegate cellDidEndMovingIncollectionView:self];
            }

 

 

 

 

 

2、顯示cell,移除截圖

 

/**
 *  拖拽結束,顯示cell,並移除截圖
 */
- (void)didEndDraging{
  
    UICollectionViewCell *cell = [self cellForItemAtIndexPath:_originalIndexPath] ;
    cell.hidden = NO;
    cell.alpha = 0;
    [UIView animateWithDuration:0.2 animations:^{
        _snapshot.center = cell.center;
        _snapshot.alpha = 0;
        _snapshot.transform = CGAffineTransformIdentity;
        cell.alpha = 1;
    } completion:^(BOOL finished) {
        cell.hidden = NO;
        [_snapshot removeFromSuperview];
        _snapshot = nil;
        _originalIndexPath = nil;
        _relocatedIndexPath = nil;
    }];
}

 

 

 

 

 

iOS拖拽移動UICollectionView下載地址:http://download.csdn.net/detail/lovechris00/9587439

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章