Set up a UICollectionView delete button in Swift

2019-04-17 11:35发布

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

2条回答
做个烂人
2楼-- · 2019-04-17 12:07
- (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()
}
查看更多
贼婆χ
3楼-- · 2019-04-17 12:20
serviceView.collectionArray.removeAtIndex(path.row)
serviceView.collectionView.deleteItemsAtIndexPaths([path])
查看更多
登录 后发表回答