Solution: Use 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;
数组的内容:
self.alletitels
包含一个字符串:“Activity Title”
self.allesubtitels
包含一个字符串:“Activity Subtitle”
self.alleimages
包含一个 url:“http://m2.myhappygames.com//files/pics/0/Paranormal_Shark_Activity_3.jpg”
谁能告诉我滚动延迟的原因是什么?
最佳答案
问题是每次调用 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;
_imageCahce 是您可以实现的 View Controller 的实例变量。
希望这对您有所帮助,干杯!
关于ios - 向上滚动时 UITableView 有延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18872791/