CollectionView中的单元格重新排序

CollectionView中的单元格重新排序

我试图对collectionView中的单元格重新排序,但是没有调用collection View delgate方法。
我已经正确设置了代表。



这是我的工作代码。

- (void)viewDidLoad {
    [super viewDidLoad];
    UILongPressGestureRecognizer *longGesture=[[UILongPressGestureRecognizer alloc] init];
    [longGesture addTarget:self action:@selector(handleGesture:)];
    [self.collectionView addGestureRecognizer:longGesture];
    NSLog(@"The array is %@",dataArray);
    self.collectionView.delegate=self;
    [_collectionView reloadData];
    // Do any additional setup after loading the view, typically from a nib.
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [dataArray count];
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
    cell.cellImageView.image = [dataArray objectAtIndex:indexPath.row];;

    return cell;
}

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


- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath*)destinationIndexPath{
    UIImage *sourceImage = [dataArray objectAtIndex:sourceIndexPath.row];
    UIImage *destImage =  [dataArray objectAtIndex:destinationIndexPath.row];
    [arr insertObject:destImage atIndex:sourceIndexPath.row];
    [arr insertObject:sourceImage atIndex:destinationIndexPath.row];



}

-(void)handleGesture:(UILongPressGestureRecognizer*)gesture{
    switch (gesture.state) {
        case UIGestureRecognizerStateBegan:{
            NSIndexPath *indexPath=[self.collectionView indexPathForItemAtPoint:[gesture locationInView:self.collectionView]];
            if(indexPath!=nil)
                [self.collectionView beginInteractiveMovementForItemAtIndexPath:indexPath];
            break;
        }
        case UIGestureRecognizerStateChanged:{
            [self.collectionView updateInteractiveMovementTargetPosition:[gesture locationInView:self.collectionView]];
        }
        case UIGestureRecognizerStateEnded:{

            [self.collectionView endInteractiveMovement];
        }

        default:
            [self.collectionView cancelInteractiveMovement];
            break;
    }
}

最佳答案

在每个case语句中添加一个break,您的代码将正常运行!

可能是将Swift示例代码转换为Objective C的结果。

10-06 01:19