我在 View 顶部有一个自定义选项卡,用户可以在其中来回切换两个 View 。这两个 View 都包含 UICollectionView 动态填充来自服务器的数据。据我了解,如果 numberOfItemInSection
在调用 [collectionView reloadData]
时返回 0,则不会调用 cellForItemAtIndexPath
。换句话说,如果 cellForItemAtIndexPath
被调用,这意味着源中有一些数据。下面是我在从一个 View 切换到另一 View 时使用的一些代码。
- (void)refresh
{
[self.collectionView setContentOffset:CGPointZero];
[self.data removeAllObjects];
[self.refreshControl beginRefreshing];
if (self.collectionView.contentOffset.y == 0) {
[UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^(void){
self.collectionView.contentOffset = CGPointMake(0, -MPViewHeight(self.refreshControl));
} completion:^(BOOL finished){
}];
}
[self.collectionView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
[self requestToServerAtIndex:0];
}
- (void) requestToServerAtIndex:(NSInteger)index
{
@weakify(self)
[[self.serverHelper getData:index requestCount:20] subscribeNext:^(id JSON) {
@strongify(self)
NSArray *data = [ParserForJSON parse:JSON];
if(data.count != 20) {
self.moreData = NO;
}
[self.data addObjectsFromArray:data];
[self.collectionView reloadData];
[self.refreshControl endRefreshing];
} error:^(NSError *error) {
}];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return self.data.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
CustomData *data = [self.data objectAtIndex:indexPath.row];
CustomCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
///.... some cell configuration
return cell;
}
但是,当它尝试访问碰巧为空的数据源时,我在 cellForItemAtIndexPath
上随机崩溃。令人惊讶的是,当我当时在控制台上检查时,数据源不为空。所以我的疯狂猜测是存在一些时间问题。我想对这种模棱两可的行为得到一些深入的解释。
最佳答案
当您调用refresh
方法时,您会删除所有data
对象,因此当您调用cellForItemAtIndexPath
时, 中没有数据数据
来源。这就是调用 id object = [data objectAtIndex:indexPath.row]
时返回 nil
的原因。因此,请确保在 requestToServerAtIndex
之后真正生成新数据,然后删除旧对象并更新 UI。
编辑:
尝试去掉[self.collectionView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
来测试,这个方法应该调用cellForItemAtIndexPath
关于ios - 调用了 UICollectionView cellForItemAtIndexPath 但数据源为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32172720/