Как удалить элемент из UICollectionView с помощью indexpath.row
У меня есть представление коллекции, и я попытался удалить ячейку из представления коллекции по методу didSelect.I удалось, используя следующий метод
[colleVIew deleteItemsAtIndexPaths:[NSArray arrayWithObject:indexPath]];
Но теперь мне нужно удалить элемент при нажатии кнопки из CellView 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. Так что анимация расположения ячеек после удаления не существует.
Пожалуйста, предложите идею заранее.
Ответы
Ответ 1
-(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) {
}];
}
Попробуйте это. Это может сработать для вас.
Ответ 2
Решение Swift 3:
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)
Ответ 3
[array removeObjectAtIndex:[indexPath row]];
[collection reloadData]; // Collection is UICollectionView
Попробуйте это.
Ответ 4
[array removeObjectAtIndex:[indexPath row]];
[self.collectionView deleteItemsAtIndexPaths:@[indexPath]];
Обычно это нормально... Вы можете видеть этот пост, он имеет дело с тем же вопросом.
Ответ 5
Я получил ответ.
Создайте кнопку в CollectionViewCell//Я назвал ее как 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]];
}
Ответ 6
swift 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)
})
}