【问题标题】:UICollectionView takes a long time to refresh dataUICollectionView 刷新数据耗时较长
【发布时间】:2013-05-07 12:56:54
【问题描述】:

这是对你们所有人的挑战......

我的UIViewController 内有一个UICollectionView,女巫正在正确加载。 我还有一个自定义的UICollectionViewCell 类女巫包含一个UIButton

我从我的服务器中检索了一个带有一些 UIImage 对象的 NSArray,以便将一个背景图像分配给我的自定义 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 有标题。自定义标题。此时只需一个UIView 和一个UILabel

- (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 和 Time Profiler 来确定时间花在哪里。
  • 好吧,Time Profiler 说问题出在这里: UserPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"userPhotoCell" forIndexPath:indexPath];... reusableCell... 也许我应该包括“如果( 单元格 == nil )"?

标签: ios uicollectionview reloaddata


【解决方案1】:

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

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

现在,UICollectionView 会根据需要立即更新。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-16
    • 2014-11-28
    • 1970-01-01
    • 2011-10-05
    • 2016-06-07
    • 1970-01-01
    • 1970-01-01
    • 2013-01-22
    相关资源
    最近更新 更多