0

I am building an app that uses a collection view to display data that can be deleted by users.

In the prototype cell, I created a button that now appears in every cell that is created (a small X). How can I set the button up to tell me which cell should be deleted (like indexPath.row)?

In principle, I want to do something like this, but in Swift: link

I'd be grateful for any help! Thanks

Community
  • 1
  • 1
GJZ
  • 2,482
  • 3
  • 21
  • 37

2 Answers2

4
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ...
    UIButton *myButton = [[UIButton alloc] initWithFrame:CGRectMake(123, 123, 40, 40)];
    [myButton setTitle:@"X" forState:UIControlStateNormal];
    [myButton setBackgroundImage:[UIImage imageNamed:@"cellDeleteBtn.png"] forState:UIControlStateNormal];
    [myButton setTag:indexPath.row];
    [myButton addTarget:self action:@selector(deleteCellFromButton:) forControlEvents:UIControlEventTouchUpInside];
    [cell addSubview:myButton];
    return cell;
}

- (void)deleteCellFromButton:(UIButton *)button
{
    [myMutableArray deleteItemAtIndex:button.tag];
    [collectionView reloadData];
}

Here is a Swift version:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    var myButton: UIButton = UIButton(frame: CGRectMake(123, 123, 40, 40))
    myButton.setTitle("X", forState: UIControlStateNormal)
    myButton.setBackgroundImage(UIImage.imageNamed("cellDeleteBtn.png"), forState: UIControlStateNormal)
    myButton.setTag(indexPath.row)
    myButton.addTarget(self, action: "deleteCellFromButton:", forControlEvents: UIControlEventTouchUpInside)
    cell.addSubview(myButton)
    return cell
}

func deleteCellFromButton(button: UIButton) {
    myMutableArray.deleteItemAtIndex(button.tag)
    collectionView.reloadData()
}
nayem
  • 7,285
  • 1
  • 33
  • 51
emotality
  • 12,795
  • 4
  • 39
  • 60
0
serviceView.collectionArray.removeAtIndex(path.row)
serviceView.collectionView.deleteItemsAtIndexPaths([path])
Bhavin Bhadani
  • 22,224
  • 10
  • 78
  • 108