Shawn
Shawn

Reputation: 667

Deleting selected cells in uicollectionview

I have placed a button within a uicollectionviewcell and when that button is pressed, it is programmatically setting the cell as selected.

- (void) deleteItem:(id)sender
{
    self.selected = YES;
    [self.cellOptionsDelegate deleteItem];
}

It then delegates to the uicollectionviewcontroller to deleted the item that is selected.

- (void) deleteItem
{
    NSArray* selectedItemsIndexPaths = [self.collectionView indexPathsForSelectedItems];

    // Delete the items from the data source.
    [self.taskArray removeObjectAtIndex:[[selectedItemsIndexPaths objectAtIndex:0] row]];

    // Now delete the items from the collection view.
    [self.collectionView deleteItemsAtIndexPaths:selectedItemsIndexPaths];

}

However, when i get the selected items using the uicollectionview method indexPathsForSelectedItems, it is not seeing that I have selected the item and the list is empty. I am using the press to select delegate method for another functionality so I was hoping to do something along the lines of what I explained above. Is there a way to make this work or a better way to inform the controller that the button pressed in the cell was tied to a cell at a specific index path?

Thank you.

Upvotes: 3

Views: 3143

Answers (3)

Ofir Malachi
Ofir Malachi

Reputation: 1286

animated:

[self.collectionView performBatchUpdates:^ {
      [_array removeObject:file];            
      [self.collectionView deleteItemsAtIndexPaths:@[indexPath]];
} completion:nil];

Upvotes: 0

Shawn
Shawn

Reputation: 667

Solved by sending the cell through the delegate method and using this:

    NSIndexPath* indexPath = [self.collectionView indexPathForCell:cell];

Upvotes: 1

Avt
Avt

Reputation: 17053

Just send a cell pointer from your cell's deleteItem method

- (void) deleteItem:(id)sender
{
    self.selected = YES;
    [self.cellOptionsDelegate deleteItem:self];
}

and change uicollectionviewcontroller's method to

- (void) deleteItem:(UICollectionViewCell*)cellToDelete
{
    NSIndexPath indexPathToDelete = [self indexPathForCell: cellToDelete];

    // Delete the items from the data source.
    [self.taskArray removeObjectAtIndex:[indexPathToDelete row]];

    // Now delete the items from the collection view.
    [self.collectionView deleteItemsAtIndexPaths:@[indexPathToDelete]];

} 

Do not forget to update '(void) deleteItem:(UICollectionViewCell*)cellToDelete' declaration in your *.h file.

Upvotes: 2

Related Questions