向上滚动时UITableView是滞后的

SDW*_*SDW 14 objective-c uitableview ios

解决方案:使用SDWebImage:https://github.com/rs/SDWebImage

我有一个UITableView,在滚动时变得非常迟钝.我发现当我正在使用的图像重新出现在屏幕上时会出现延迟.

我正在使用自定义UITableViewCell.这也是它滞后的原因吗?

我的自定义UITableViewCell:

在此输入图像描述

我的代码:

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

NSString *CellIdentifier = [NSString stringWithFormat:@"Cell%d%d",indexPath.row,indexPath.section];


tableViewCellActiviteiten *cell = (tableViewCellActiviteiten *)[self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil)
{

    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"tableViewCellActiviteiten" owner:self options:nil];
    cell = (tableViewCellActiviteiten *)[nib objectAtIndex:0];
}


cell.thetitle.text = [self.alletitels objectAtIndex:indexPath.row];
cell.thesubtitle.text = [self.allesubtitels objectAtIndex:indexPath.row];

NSString * imagePath = [self.alleimages objectAtIndex:indexPath.row];

NSURL * imageURL = [NSURL URLWithString:imagePath];
NSData * imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage * image = [UIImage imageWithData:imageData];

cell.image.image = image;

return cell;
Run Code Online (Sandbox Code Playgroud)

}

数组的内容:

self.alletitels 包含一个字符串:"Activity Title"

self.allesubtitels 包含一个字符串:"Activity Subtitle"

self.alleimages包含一个网址:" http://m2.myhappygames.com//files/pics/0/Paranormal_Shark_Activity_3.jpg "

任何人都可以建议可能导致延迟滚动的原因是什么?

小智 9

问题是,每次tableView: cellForRowAtIndexPath:调用方法时,您的代码都会生成一个图像.每次单元格出现在屏幕上时都会调用此方法,因此如果您滚动速度非常快,此方法将开始同步分配大量图像,这将减慢滚动速度.

作为一种快速解决方案,在View Controller中实现NSCache并将图像存储在其中.

UIImage *image = [_imageCache objectForKey:@indexPath.row];
if (image == nil) {
    NSString * imagePath = [self.alleimages objectAtIndex:indexPath.row];
    NSURL * imageURL = [NSURL URLWithString:imagePath];
    NSData * imageData = [NSData dataWithContentsOfURL:imageURL];
    image = [UIImage imageWithData:imageData];
    [_imageCache setObject:image forKey:@indexPath.row];
}

cell.image.image = image;
Run Code Online (Sandbox Code Playgroud)

_imageCahce是您可以实现的视图控制器的实例变量.

希望这会有所帮助,欢呼!

  • 这个解决方案的唯一问题是,它不会工作;)您需要异步加载图像并可能将它们保存到缓存中.如果没有图像,则显示占位符.异步加载器的完成块必须检查该单元是否可见.如果是这样,请设置图像,否则不执行任何操作.当图像缓存耗尽时,您需要一个更复杂的缓存,只能保存少量图像但_preloads_和_prepares_图像*前面*.这样,无论何时要绘制任何单元格,图像都已准备好并快速渲染. (2认同)

Mic*_*ann 6

这两行:

NSData * imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage * image = [UIImage imageWithData:imageData];
Run Code Online (Sandbox Code Playgroud)

是什么会大大降低您的表性能.

每次刷新该单元格时,您都在同步获取和加载图像数据.

以某种方式缓存(或保存本地)要显示的图像会更聪明.如果它们没有保存在本地或缓存中,那么只需要获取这些图像(并在该" cellForRowAtIndexPath:"方法之外进行异步处理).