在Swift中设置UICollectionView删除按钮 [英] Set up a UICollectionView delete button in Swift

查看:801
本文介绍了在Swift中设置UICollectionView删除按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个使用集合视图来显示可以被用户删除的数据的应用程序。

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

在原型单元格中,我创建了一个现在出现的按钮在每个创建的单元格中(小X)。如何设置按钮告诉我应删除哪个单元格(如indexPath.row)?

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)?

原则上,我想做类似的事情,但是Swift:链接

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


我将不胜感激任何帮助!谢谢

I'd be grateful for any help! Thanks


推荐答案

- (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];
}

这是一个Swift版本:

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

这篇关于在Swift中设置UICollectionView删除按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆