UICollectionView需要很长时间才能刷新数据。

3

这里有一个挑战给大家...

我在我的UIViewController中有一个正确加载的UICollectionView。我也有一个自定义的UICollectionViewCell类,其中包含一个UIButton

我从服务器检索到一个NSArray,其中包含一些UIImage对象,以便将一个背景图像分配给我的自定义UICollectionViewCell的按钮。

这是我cellForItemAtIndexPath函数的代码:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;
{
    UserPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"userPhotoCell" forIndexPath:indexPath];

    if (indexPath.section == 0) {
        [[cell imageButton] setBackgroundImage:[userPublicImages objectAtIndex:indexPath.row] forState:UIControlStateNormal];
    } else {
        [[cell imageButton] setBackgroundImage:[userPrivateImages objectAtIndex:indexPath.row] forState:UIControlStateNormal];
    }

    return cell;
}

如您所见,这非常简单。

下面涉及到一种奇怪的行为:如果我将所有自定义的UICollectionViewCell放在UICollectionView的一个部分中,性能还可以接受...

有什么想法吗?

一些额外的信息: UICollectionView有标题。 自定义标题。 目前只是一个带有UILabelUIView

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *reusableView = nil;

    if (kind == UICollectionElementKindSectionHeader) {
        UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"collectionHeader" forIndexPath:indexPath];
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, [headerView frame].size.width, 40.0f)];
        if (indexPath.section == 0) {
            [titleLabel setText:NSLocalizedStringFromTable (@"collectionTitle_publicPhotos", [[NSLocale preferredLanguages] objectAtIndex:0] , @"")];
        } else {
            [titleLabel setText:NSLocalizedStringFromTable (@"collectionTitle_privatePhotos", [[NSLocale preferredLanguages] objectAtIndex:0] , @"")];
        }
        [headerView addSubview:titleLabel];

        reusableView = headerView;
    }

    return reusableView;
}

你应该使用Instruments和时间分析器来确定时间花费在哪里。 - Mike Weller
时间分析器(Time Profiler)显示问题出在这里:UserPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"userPhotoCell" forIndexPath:indexPath];...可重用单元(reusableCell)...也许我应该加上 "if ( cell == nil )"? - Jorge Ramos
1个回答

14

我觉得我找到答案了。由于某种奇怪的原因,[collectionView reloadData] 没有在主线程上执行。因此,我的解决方案就是这么简单:

我认为我已经找到了答案。由于某种奇怪的原因,[collectionView reloadData]没有在主线程上触发。所以,我的解决方案就是这样简单:

dispatch_async(dispatch_get_main_queue(), ^{
        [_collectionUserPhotos reloadData];
    });

现在,UICollectionView会立即按预期进行更新。

一些注意事项:这个[collectionView reloadData]是在使用AFNetworking后,在使用队列的自定义类的委托方法中调用的。希望这可以帮助你。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接