iOS UICollectionViewCell 的拖动
生活随笔
收集整理的這篇文章主要介紹了
iOS UICollectionViewCell 的拖动
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
1.長按cell的情況下實現(xiàn)拖動,所以理應想到用長按手勢。
2.既然實現(xiàn)移動cell,就要看看UICollectionView 有沒有方法或者協(xié)議可以移動的。通過查看UICollectionView的協(xié)議方法,可以在UICollectionViewDataSource中看到有兩個方法。
- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath; - (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath*)destinationIndexPath;?3.OK 知道了以上兩個步驟,那么就可以開始寫代碼了。
// 設置手勢 - (void)setupGesture {UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handlelongGesture:)];[self.collectionView addGestureRecognizer:longPress]; } - (void)handlelongGesture:(UILongPressGestureRecognizer *)longGesture {//判斷手勢狀態(tài)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]; }
注:_dataSource 是你的數據源。
?
轉載于:https://www.cnblogs.com/peaker-wu/p/5359510.html
總結
以上是生活随笔為你收集整理的iOS UICollectionViewCell 的拖动的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: javascript:void(0)和j
- 下一篇: iOS中点与像素