前段時(shí)間在做商品收藏的時(shí)候,用UICollectionView展示收藏商品,刪除收藏用到collection的刪除方法。
[self.dataAry removeObjectAtIndex:indexPath.row];
[collectionView deleteItemsAtIndexPaths:@[indexPath]];
發(fā)現(xiàn)一個(gè)問(wèn)題,collection執(zhí)行deleteItems后只會(huì)調(diào)用numberOfItemsInSection刷新一下item的數(shù)量,并不會(huì)調(diào)用cellForItemAtIndexPath來(lái)刷新數(shù)據(jù),(因?yàn)橹皇莿h除,item的內(nèi)容不會(huì)變,只會(huì)動(dòng)一下位置),這就導(dǎo)致了一個(gè)問(wèn)題,當(dāng)我刪除到最后一個(gè)cell的時(shí)候,發(fā)現(xiàn)數(shù)組越界。原因是dataAry只剩一個(gè)數(shù)據(jù),但是indexPath.row=1。
解決方案:
[collectionView performBatchUpdates:^{
[self.dataAry removeObjectAtIndex:indexPath.row];
[collectionView deleteItemsAtIndexPaths:@[indexPath]];
}completion:^(BOOL finished){
[collectionView reloadData];
}];
每次刪除執(zhí)行完后刷新數(shù)據(jù)。大家有其他解決辦法歡迎指正。