gpt4 book ai didi

ios - CollectionView 中的 UIImageView 在图像下载后不更新 UI

转载 作者:行者123 更新时间:2023-11-29 02:21:08 25 4
gpt4 key购买 nike

我有一个带有 Collection View 的应用程序,它应该显示图像缩略图。该应用程序首先需要下载一个 json 字符串,其中包含从中下载缩略图的 url。

我遇到的问题是 Collection View 单元格没有显示图像,尽管这些图像是由代码下载的。

代码

查看 Controller 界面:

@interface NewsfeedController : UICollectionViewController <UICollectionViewDataSource, UICollectionViewDelegate>

@property (weak, nonatomic) IBOutlet UILabel *rawNewsfeed;
@property NSMutableArray *newsfeedPosts;
@property (weak, nonatomic) IBOutlet UICollectionView *newsfeedCollectionView;

@end

Controller 的 viewDidLoad 包括以下行:

[self.newsfeedCollectionView registerClass:[PostCellView class] forCellWithReuseIdentifier:@"PostCellView"];

该单元格是自定义单元格,由此类定义:

PostCellView.h

@interface PostCellView : UICollectionViewCell
@property (nonatomic) IBOutlet UIImageView *posterImageView;

@end

在 View Controller 中,我实现了 cellForItemAtIndexPath 方法,如下所示:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
PostCellView *postCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PostCellView" forIndexPath:indexPath];
if(!postCell){
postCell = [[PostCellView alloc]init];
}

long row = indexPath.row;
PostModel *post = [self.newsfeedPosts objectAtIndex:row];
NSURL *posterUrl = [NSURL URLWithString:post.media[@"poster"]];

NSURLSessionDataTask *getPosterImage = [[NetworkHelper getInstance].session dataTaskWithURL:posterUrl completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
UIImage *posterImage = [UIImage imageWithData:data];
postCell.posterImageView = [[UIImageView alloc] initWithImage:posterImage];
});
}];
[getPosterImage resume];

return postCell;
}

如您所见,我正在异步下载缩略图图像,因此在下载完成后,我尝试通过在主队列的 dispatch_async 中设置 posterImageView 来更新 UI。但是,UI 永远不会使用缩略图进行更新。在调试时查看 View 层次结构,应用程序确实创建了我期望的 8 个单元格,但同样,图像永远不会显示。

因此,从本质上讲,一旦这些图像是通过异步过程下载的,我就无法让我的应用程序 Collection View 中的单元格显示它们相应的图像。

最佳答案

根据 rdelmar 的上述评论,问题出在这一行:

postCell.posterImageView = [[UIImageView alloc] initWithImage:posterImage];

我正在初始化一个已声明为 IBOutlet 的 ImageView 。所以我将该行更改为以下内容,图像开始出现:

postCell.posterImageView.image = posterImage;

关于ios - CollectionView 中的 UIImageView 在图像下载后不更新 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28120381/

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