如何删除UICollectionView上的单元格

时间:2015-03-06 14:20:18

标签: objective-c uicollectionview

我在每个单元格上创建了​​一个按钮,onClick让用户删除我的UICollectionView的单元格,我在其中初始化单元格,我使用以下代码将indexPath.item传递给按钮方法:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];



    // Configure the cell
    FidelityProducts *item = _feedItems[indexPath.item];
    NSLog(@"index dell'item:%ld", (long)indexPath.item);

    cell.deleteProduct.tag = indexPath.item;
    NSLog(@"TAG ASSEGNATO AL BOTTONE: %d",cell.deleteProduct.tag);
    [cell.deleteProduct addTarget:self action:@selector(DeleteProductFromArray:)
     forControlEvents:UIControlEventTouchUpInside];

    return cell;
}

然后在DeleteProductFromArray我创建了以下逻辑以删除单元格:

- (void)DeleteProductFromArray:(UIButton *)button {

    [_feedItems removeObjectAtIndex:button.tag];

    //check for the Column (can be 0 or 1)
    if(button.tag % 2 == 0)
    {
        IndexColumn = 0;
    }
    else
    {
        IndexColumn = 1;
    }

    //check for the Row
    if(button.tag > 1)
    {
        IndexRow = button.tag/2;
    }
    if(button.tag <= 1)
    {
        IndexRow = 0;
    }
    NSLog(@"button column =%d", IndexColumn);
    NSLog(@"button row =%d", IndexRow);

    [self.customCollectionView deleteItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:IndexColumn inSection:IndexRow]]];

}

现在,我知道这会导致问题,因为当我从NSMutableArray中删除项目时按钮标签没有更新但我只需要知道为什么我第一次尝试删除一个Cell的数字1和2被取消,但如果我点击一个单元格&gt; 3应用程序因以下错误而崩溃:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'attempt to delete item 0 from section 2, but there are only 1 sections before the update

1 个答案:

答案 0 :(得分:0)

我是愚蠢的。 所有的按钮逻辑都没用,我忘了检查部分的数量,它们总是0。 改变了

[self.customCollectionView deleteItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:IndexColumn inSection:IndexRow]]];

要:

 [self.customCollectionView deleteItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:button.tag inSection:0]]];

一切都按预期工作..