gpt4 book ai didi

ios - 从服务器加载图像时 UITableView 滚动卡住

转载 作者:行者123 更新时间:2023-12-01 17:26:35 32 4
gpt4 key购买 nike

我正在使用此代码使用自定义单元格在 UITableView 中加载我的图像

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"CustomCell";

CustomCell *cell = (CustomCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {

NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
for (id currentObject in topLevelObjects) {
if ([currentObject isKindOfClass:[CustomCell class]]) {
cell = (CustomCell *) currentObject;
break;
}
}

NSString *tempString = [arrayThumbs objectAtIndex:indexPath.row];
NSURL *imageURL = [NSURL URLWithString:tempString];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:imageData];
cell.img.image = image;

}

return cell;
}

使用上面的代码,上下滚动时没有问题,但是图像显示不正确,表格中重复了一些图像,例如如果数组包含从 1 到 10 的 10 个图像并且数组是正确的按顺序,我在表格中得到的图像类似于 1 、 2 、 3 、 4 、 3 、 3 、 1 、 10 、 8 、 9

但是当我使用这段代码时
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"CustomCell";

CustomCell *cell = (CustomCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {

NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
for (id currentObject in topLevelObjects) {
if ([currentObject isKindOfClass:[CustomCell class]]) {
cell = (CustomCell *) currentObject;
break;
}
}

}

NSString *tempString = [arrayThumbs objectAtIndex:indexPath.row];
NSURL *imageURL = [NSURL URLWithString:tempString];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:imageData];
cell.img.image = image;

return cell;
}

图像排序很好,没有重复,但是当我滚动到表格底部然后滚动回顶部表格卡住 2 或 3 秒

知道如何解决这个问题吗?

该数组包含图像的链接,如 http://www.website.com/image.jpg

自定义单元格包含 IBOutlet UIImageView 60x60 并且从服务器加载的图像也是 60x60

最佳答案

尝试以下代码在线程中下载图像。

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString *tempString = [arrayThumbs objectAtIndex:indexPath.row];
NSURL *imageURL = [NSURL URLWithString:tempString];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:imageData];
dispatch_async(dispatch_get_main_queue(), ^{
cell.img.image = image;
});
});

关于ios - 从服务器加载图像时 UITableView 滚动卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15458838/

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