I am trying to reorder the cell in collectionView, But the collection View delgate method is not getting called. I have set the delegate properly.
- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath )sourceIndexPath toIndexPath:(NSIndexPath)destinationIndexPath
Here is my working Code.
- (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;
}
}
Add a break to every case statement and your code will run fine!
This gotcha is probably the result of translating Swift example code into Objective C.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With