I have a UICollectionView
that I populate from my Image Library.
I want to be able to delete a cell from the collection by using a UILongPressGestureRecognizer
on the cell. The UILongPressGestureRecognizer
is working.
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"Selected cell = %ld",(long)indexPath.item);
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(activateDeletionMode:)];
longPress.delegate = self;
[collectionView addGestureRecognizer:longPress];
}
- (void)activateDeletionMode:(UILongPressGestureRecognizer *)gr
{
if (gr.state == UIGestureRecognizerStateBegan)
{
NSLog(@"delete mode");
}
}
In your case try this
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"Selected cell = %ld",(long)indexPath.item);
UILongPressGestureRecognizer * longPres
= [[UILongPressGestureRecognizer alloc]
initWithTarget:self action:@selector(activateDeletionMode:)];
longPres.minimumPressDuration = .5; //seconds
longPres.delegate = self;
[self.collectionView addGestureRecognizer: longPres];
}
- (void)activateDeletionMode:(UILongPressGestureRecognizer *)gr
{
if (gr.state == UIGestureRecognizerStateBegan)
{
NSLog(@"delete mode");
}
}
in other case you can try this
//add long press gesture to collectionView
UILongPressGestureRecognizer *longpress
= [[UILongPressGestureRecognizer alloc]
initWithTarget:self action:@selector(handleLongpressMethod:)];
longpress.minimumPressDuration = .5; //seconds
longpress.delegate = self;
[self.collectionView addGestureRecognizer: longpress];
}
then handle the action
-(void) handleLongpressMethod:(UILongPressGestureRecognizer *)gestureRecognizer
{
if (gestureRecognizer.state != UIGestureRecognizerStateEnded) {
return;
}
CGPoint pt = [gestureRecognizer locationInView:self.collectionView];
NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:pt];
if (indexPath == nil){
NSLog(@"couldn't find index path");
} else {
// get the cell at indexPath (the one you long pressed)
UICollectionViewCell* cell =
[self.collectionView cellForItemAtIndexPath:indexPath];
// work with the cell
}
delete
[self.youritemarray removeObjectAtIndex:indexPathh];
[collectionView reloadData];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.