gpt4 book ai didi

ios - UICollectionView - 删除所有项目或更新以刷新它

转载 作者:行者123 更新时间:2023-11-29 10:46:20 26 4
gpt4 key购买 nike

我正在开发一个基于 UICollectionView 的应用程序,我通过 - 加载它

    NSUInteger newNumCells = [self.imageArray count];
NSIndexPath* newIndexPath;

NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
[indexPaths removeAllObjects];

for (int i = 0; i < newNumCells; ++i) {
newIndexPath = [NSIndexPath indexPathForItem:i inSection:0];
[indexPaths addObject:newIndexPath];
}

self.indexPaths = indexPaths;
[self.collectionView insertItemsAtIndexPaths:indexPaths];
[self.collectionView reloadData];

它运行良好。

然后我在同一个页面有另一个搜索功能,所以当我从服务器得到新的搜索结果时,self.imageArray 内容改变了,我想刷新当前 UICollectionView, 例如,删除所有项目,并从当前的 self.imageArray 插入新项目,但是当我删除项目时,总是崩溃 -

[self.collectionView performBatchUpdates:^{

//self.indexPaths = [self.collectionView indexPathsForVisibleItems];
//[self.imageArray removeAllObjects];

self.indexPaths = [self.collectionView indexPathsForVisibleItems];
[self.imageArray removeAllObjects];
[self.collectionView deleteItemsAtIndexPaths:self.indexPaths];
[self.collectionView.collectionViewLayout invalidateLayout];

//[self.collectionView reloadData];

//[self.collectionView deleteItemsAtIndexPaths:[self.collectionView indexPathsForVisibleItems]];

} completion:nil];

崩溃信息 -

Assertion failure in -[UICollectionViewData validateLayoutInRect:], /SourceCache/UIKit_Sim/UIKit-2903.2/UICollectionViewData.m:341
2014-03-07 11:47:48.450 pixcell8[9089:a0b] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UICollectionView recieved layout attributes for a cell with an index path that does not exist: <NSIndexPath: 0xb4a8430> {length = 2, path = 0 - 0}'

所以我想问一下如何用新数据刷新UICollectionView?谢谢。

更新:这个错误是因为我使用了自定义布局,它有一些错误的逻辑,现在已经修复了。

最佳答案

加载 Collection View 与 TableView 非常相似。使用委托(delegate)和数据源协议(protocol)来处理其中的大部分。

对于你来说是这样的

 self.collectionView.dataSource = self;

然后在数据源方法中

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return self.imageArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
//Set up and return your cell
}

当您想要更改内容时,您可以替换或更新 imageArray 和 reloadData 的内容。

来自 API 的新内容进来

[self.imageArray removeAllObjects];
[self.imageArray addObjectsFromArray:apiResponseArray];
[self.collectionView reloadData];

还有其他方法可能更有效,但这应该可以帮助您入门。正确完成基本设置后,您可以根据需要使用其他方法进行插入和批处理。

关于ios - UICollectionView - 删除所有项目或更新以刷新它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22241143/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com