如何用indexpath.row从UICollectionView中删除一个项目

我有一个集合视图,我试图从didSelect方法的集合视图中删除一个单元格。我成功地使用了下面的方法

[colleVIew deleteItemsAtIndexPaths:[NSArray arrayWithObject:indexPath]]; 

但现在我需要删除button上的项目单击CollectionView Cell.Here我只得到indexpath.row。 从这我不能删除项目。 我试过这样

 -(void)remove:(int)i { NSLog(@"index path%d",i); [array removeObjectAtIndex:i]; NSIndexPath *indexPath =[NSIndexPath indexPathForRow:i inSection:0]; [colleVIew deleteItemsAtIndexPaths:[NSArray arrayWithObject:indexPath]]; [colleVIew reloadData]; } 

但是需要重新加载CollectionView,所以删除后的单元格排列animation就不存在了。 请提出一个想法..提前感谢

 -(void)remove:(int)i { [self.collectionObj performBatchUpdates:^{ [array removeObjectAtIndex:i]; NSIndexPath *indexPath =[NSIndexPath indexPathForRow:i inSection:0]; [self.collectionObj deleteItemsAtIndexPaths:[NSArray arrayWithObject:indexPath]]; } completion:^(BOOL finished) { }]; } 

尝试这个。 它可能适合你。

Swift 3解决scheme:

 func remove(_ i: Int) { myObjectsList.remove(at: i) let indexPath = IndexPath(row: i, section: 0) self.collectionView.performBatchUpdates({ self.collectionView.deleteItems(at: [indexPath]) }) { (finished) in self.collectionView.reloadItems(at: self.collectionView.indexPathsForVisibleItems) } } 

和示例删除调用:

 self.remove(indexPath.row) 
 [array removeObjectAtIndex:[indexPath row]]; [collection reloadData]; // Collection is UICollectionView 

尝试这个。

[array removeObjectAtIndex:[indexPath row]];

[self.collectionView deleteItemsAtIndexPaths:@[indexPath]];

通常没关系…你可以看到这个post ,它处理相同的主题。

我得到了答案

在CollectionViewCell中创build一个button//我将它命名为removeBtn

然后在CollectionView Delegate中

  - cellForItemAtIndexPath [cell.removeBtn addTarget:self action:@selector(RemovePrssd:) forControlEvents:UIControlEventTouchUpInside]; 

然后添加该方法

 -(void)RemovePrssd:(id)sender{ UIView *senderButton = (UIView*) sender; NSIndexPath *indexPath = [colleVIew indexPathForCell: (UICollectionViewCell *)[[senderButton superview]superview]]; [array removeObjectAtIndex:indexPath.row]; [colleVIew deleteItemsAtIndexPaths:[NSArray arrayWithObject:indexPath]]; } 

迅捷3:

 func remove(index: Int) { myObjectList.remove(at: index) let indexPath = IndexPath(row: index, section: 0) collectionView.performBatchUpdates({ self.collectionView.deleteItems(at: [indexPath]) }, completion: { (finished: Bool) in self.collectionView.reloadItems(at: self.collectionView.indexPathsForVisibleItems) }) }