iOS 表视图在将图像加载到图像视图时滚动滞后



我正在使用一个名为SDWebImage的库进行异步(背景)图像加载UITableviewCell。但在滚动表格视图时仍然面临巨大的滞后。

我做错了什么吗?

加载的图像尺寸在1000x1000左右相当大

将图像加载到单元格的代码:

[cell.image sd_setImageWithURL:[NSURL URLWithString:imageUrl]
placeholderImage:[UIImage imageNamed:@"image.png"]];

在这里,我将所有信息加载到表视图单元格:

-(void)viewDidLoad{
[super viewDidLoad];
NSString *identifier = @"newsItem";
UINib *nib = [UINib nibWithNibName:@"NewsTableViewCell" bundle:nil];
[self.tableView registerNib:nib forCellReuseIdentifier:identifier];

self.dataSource = [[NewsDataSource alloc] initWithQuery:[self getQuery]
populateCell:^UITableViewCell * _Nonnull(UITableView * _Nonnull tableView,
              NSIndexPath * _Nonnull indexPath,
              FIRDataSnapshot * _Nonnull snap) {
NewsItem *newsItem = [[NewsItem alloc] initWithDictionary:snap.value];

NSURL *url = [NSURL URLWithString:newsItem.image];
NSString *imageUrl = url.absoluteString;
NSData *data = [NSData dataWithContentsOfURL:url];

NewsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
cell.image.layer.masksToBounds = YES;
cell.Title.text = newsItem.title;
cell.category.text = [newsItem.categories objectAtIndex:0];
cell.subTitle.text = newsItem.subTitle;
[cell.image sd_setImageWithURL:[NSURL URLWithString:imageUrl]
placeholderImage:[UIImage imageNamed:@"image.png"]];                          
cell.image.contentMode = UIViewContentModeScaleAspectFill;
[cell.image setFrame:CGRectMake(0,0,cell.frame.size.width,cell.frame.size.height)];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}];
[self.dataSource bindToView:self.tableView];
self.tableView.delegate = self;
}

从源代码中删除以下行,因为它会在激活 tableview 单元格期间(每次重复使用单元格时)下载图像数据。另请注意,它可能会在前台加载数据,这可能是滚动表视图时滞后的原因。

NSData *data = [NSData dataWithContentsOfURL:url];

以下代码处理表视图单元格的图像表示形式(在背景中下载图像并使其在前台可见)。因此,您的单元格中不需要上述代码。

[cell.image sd_setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:[UIImage imageNamed:@"image.png"]];

你必须删除这一行

NSData *data = [NSData dataWithContentsOfURL:url];

最新更新