【问题标题】:Need To delete cell from UICollectionView需要从 UICollectionView 中删除单元格
【发布时间】:2015-03-06 16:27:55
【问题描述】:

我无法摆脱这一点,我有一个带有自定义单元格的 UICollectionView,每个单元格都有一个 X 按钮可以从列表中删除它,我将 IndexPath.item 传递给 button.tag 并在删除函数上我'已经实现了以下方法:

- (void)DeleteProductFromArray:(UIButton *)button {
    NSLog(@"item: %d",button.tag);
    TagHelpConverted = [NSNumber numberWithInt:button.tag];
    TagHelp = button.tag;
    if(DeletedCells.count == 0)
    {
        [DeletedCells addObject:TagHelpConverted];
    }
    else
    {
        for(int i = 0; i < DeletedCells.count; i++)
        {
            if([TagHelpConverted compare:DeletedCells[i]] == NSOrderedDescending)
            {
                TagHelp--;
                NSLog(@"ho diminuito il tag di 1");
            }
        }
        [DeletedCells addObject:TagHelpConverted];
    }

    NSLog(@"valore tagHelp:%d", TagHelp);
    [_feedItems removeObjectAtIndex:TagHelp];

    [self.customCollectionView deleteItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:TagHelp inSection:0]]];
    [self.customCollectionView reloadData];

}

问题是,当滚动 UICollectionView 调用 - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { 时,我的 NSMutableArray 存储已单击的按钮具有“旧值”,与此方法分配的新值相比,应用程序会删除UICollectionView。 我在互联网上搜索有关删除 UICollectionView 单元格的帮助,但我几乎找到了任何东西,我在这方面非常努力,但我找不到摆脱的方法,如果有人有解决方案,请帮助我

【问题讨论】:

  • 小贴士:变量应该以小写开头。例如tagHelpConvertedtagHelpdeletedCells

标签: objective-c uicollectionview


【解决方案1】:

要从 collectionView 中删除单元格,您可以将它们从数据源中删除并重新加载 collectionView。您要确保您的数据源与屏幕上的内容保持同步。基本上,保持你的数据源是你想要的,然后调用 [collectionView reloadData]。

- (void)didTapDeleteCellBtn:(UIButton *)deleteCellBtn {
    UICollectionViewCell *cell = (UICollectionViewCell *)deleteCellBtn.superview.superview; // Make sure this gets the right cell for the button
    NSIndexPath *indexPath = [self.customCollectionView indexPathForCell:cell];
    id item = self.feedItems[indexPath.row];
    NSMutableArray *updatedFeedItems = [self.feedItems mutableCopy];
    [updatedFeedItems removeObject:item];
    self.feedItems = [NSArray arrayWithArray:updatedFeedItems];
    [self.customCollectionView reloadData];
}

【讨论】:

  • 非常感谢,我稍微编辑了代码,现在可以完美运行了,谢谢!
  • 这些东西最好嵌套在 UICollectionView 上的 performBatchUpdates:completion 块中