Set up a UICollectionView delete button in Swift

浪子不回头ぞ 提交于 2019-12-10 00:20:00

问题


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


回答1:


- (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()
}



回答2:


serviceView.collectionArray.removeAtIndex(path.row)
serviceView.collectionView.deleteItemsAtIndexPaths([path])


来源:https://stackoverflow.com/questions/32068216/set-up-a-uicollectionview-delete-button-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!