在Swift中设置UICollectionView删除按钮

时间:2015-08-18 09:13:47

标签: ios xcode swift uicollectionview uicollectionviewcell

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

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

原则上,我想做类似的事情,但在Swift:link

  

我会感激任何帮助!感谢

2 个答案:

答案 0 :(得分: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];
}

这是一个Swift版本:

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

答案 1 :(得分:0)

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