iOS

[toc]

UICollectionView SelectItem方法无效的原因

https://blog.csdn.net/weixin_34127717/article/details/88010800

  1. [collectionView reloadData];
  2. [collectionView layoutIfNeeded];
  3. [collectionView selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionNone];

UICollectionView删除数据更新

前段时间在做商品收藏的时候,用UICollectionView展示收藏商品,删除收藏用到collection的删除方法。

1
2
3
[self.dataAry removeObjectAtIndex:indexPath.row];

[collectionView deleteItemsAtIndexPaths:@[indexPath]];

发现一个问题,collection执行deleteItems后只会调用numberOfItemsInSection刷新一下item的数量,并不会调用cellForItemAtIndexPath来刷新数据,(因为只是删除,item的内容不会变,只会动一下位置),这就导致了一个问题,当我删除到最后一个cell的时候,发现数组越界。原因是dataAry只剩一个数据,但是indexPath.row=1。

解决方案:

1
2
3
4
5
6
7
[collectionView performBatchUpdates:^{
[self.dataAry removeObjectAtIndex:indexPath.row];
[collectionView deleteItemsAtIndexPaths:@[indexPath]];

} completion:^(BOOL finished) {
[collectionView reloadData];
}];

每次删除执行完后刷新数据。大家有其他解决办法欢迎指正。

所以为了不执行reloadData,

UICollectionView cellForItemAtIndexPath 方法不走

在storyboard 中

UICollectionView cellForItemAtIndexPath not called

被坑了好久,各种问题点查找,终于解决了

解决办法:automaticallyAdjustsScrollViewInsets

1
2
3
4
5
6
7
8
 self.automaticallyAdjustsScrollViewInsets = NO;//解决cellForItemAtIndexPath not called问题

if (@available(iOS 11.0, *)) {
self.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
} else {
// Fallback on earlier versions
self.automaticallyAdjustsScrollViewInsets = NO;
}