Search code examples
objective-cuitableviewios6uicollectionview

UICollectionView how to delete cells (equivalent of commitEditingStyle)?


I'm building my first application using UICollectionView and noticed that there isn't much I can do in terms of object deletion. For UITableView apps, there's the swipe to delete method:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } 

}

When I use GMGridView, it has behaviors similar to long press on the iPhone home screen - the view stars to shake and a delete button can be displayed, which is responsible for deleting the view. I can certainly try to replicate this behavior, but am not sure if users will "get it".

I'm interested in what are my options for letting the user delete objects from UICollectionView - do I have to implement my own delete gestures/controls, or is there something that I'm missing (or open source)?


Solution

  • I inserted this code in my view controller that includes the CollectionView and did it this way. You are probably already doing something like this with the tap gesture to detect selected cell.

    - (IBAction)didLongPressCellToDelete:(UILongPressGestureRecognizer*)gesture {
    CGPoint tapLocation = [gesture locationInView:self.myCollectionView];
    NSIndexPath *indexPath = [self.myCollectionView indexPathForItemAtPoint:tapLocation];
    if (indexPath && gesture.state == UIGestureRecognizerStateBegan) {
        NSLog(@"image with index %d to be deleted", indexPath.item);
        self.itemToBeDeleted = indexPath.item;
        UIAlertView *deleteAlert = [[UIAlertView alloc]
                                 initWithTitle:@"Delete?"
                                 message:@"Are you sure you want to delete this image?"
                                 delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Yes", nil];
        [deleteAlert show];
    
    }
    }
    
    
    - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    NSLog(@"selected button index = %d", buttonIndex);
    if (buttonIndex == 1) {
        // Do what you need to do to delete the cell 
        [self.myCollectionView reloadData];
    }
    }