gpt4 book ai didi

ios - 从 URL 为 UITableViewCell 加载图像(需要异步加载)

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:54:24 27 4
gpt4 key购买 nike

我有一个自定义类,它通过 XML 进行解析并获取图像的 URL 字符串(我将其存储在一个数组中)。然后我想检索这些字符串以加载图像并在 UITableViewCell 中显示每个图像。这是我的代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

UILabel *labelText = (UILabel *)[cell viewWithTag:1000];
labelText.text = [[self.listOfPlaceDetails objectAtIndex:indexPath.row] objectForKey:@"name"];

NSURL *imageURL = [NSURL URLWithString:[[self.listOfPlaceDetails objectAtIndex:indexPath.row]objectForKey:@"imageCell"]];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:imageData];
cell.imageView.image = image;

return cell;
}

显然,当我向下滚动表格时,应用会加载更多图片,而当图片正在加载时,用户无法执行任何操作。应用程序似乎卡住了。我要加载的图像不是很大(大约 8kb)。也许有一种方法可以在后台加载和存储它们?我还想给用户更多的自由,比如向下滚动和查看带有文本但没有图像的单元格。然后强制应用加载用户当前正在查看的单元格的图像。

是否有任何方法可以修改我的代码或任何其他解决方案以从 URL 字符串正确加载图像?

如有任何建议,我们将不胜感激。

最佳答案

尝试异步加载图像,这样主线程就不会阻塞。

您的代码如下所示:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

UILabel *labelText = (UILabel *)[cell viewWithTag:1000];
labelText.text = [[self.listOfPlaceDetails objectAtIndex:indexPath.row] objectForKey:@"name"];

NSURL *imageURL = [NSURL URLWithString:[[self.listOfPlaceDetails objectAtIndex:indexPath.row]objectForKey:@"imageCell"]];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:imageData];

dispatch_async(dispatch_get_main_queue(), ^{
cell.imageView.image = image;
});
});

return cell;
}

关于ios - 从 URL 为 UITableViewCell 加载图像(需要异步加载),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21750426/

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