关于tableView加载图片的优化

对于tableview加载大量图片时,如果不做优化,就会损耗服务器对app的性能也不好,在面试过程中面试官也比较关心这个问题,进行百度一下有以下思路:
1.在tableview正在快速滚动和缓慢滚动时,如果该图片还没有被加载,那么就要给它一个默认图,否则才进行下载图片。
注:
sdwebimage对下载的图片有缓存作用,downImageArray用于存储那些图片已经下载过的NSIndxPath,tableView属性isDragging表示正在快速滚动,isDecelerating表示正在慢速滚动,当tableView 正在滚动而且该cell 的图片还没下载的时候直接显示占位图片,

  • (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@“cell” forIndexPath:indexPath];
    if ((self.tableView.isDragging || self.tableView.isDecelerating) && ![self.downImageArray containsObject:indexPath]) {
    cell.iconView.image = [UIImage imageNamed:@“1.jpg”];
    return cell;
    }
    [cell.iconView sd_setImageWithURL:[NSURL URLWithString:_array[indexPath.row]] placeholderImage:[UIImage imageNamed:@“1.jpg”] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
    if (![self.downImageArray containsObject:indexPath]) {
    [self.downImageArray addObject:indexPath];
    }
    }];
    return cell;
    }
    //结束快速滚动,开始慢速滚动
  • (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (!decelerate) {
    [self reload];
    }
    }

//慢速滚动结束

  • (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self reload];
    }
    // 数据刷新
  • (void)reload {
    NSArray *arr = [self.tableView indexPathsForVisibleRows];
    //存储需要下载图片的indexpath
    NSMutableArray *arrToReload = [NSMutableArray array];
    for (NSIndexPath *indexPath in arr) {
    //判断该cell的图片是否已经下载
    if (![self.downImageArray containsObject:indexPath]) {
    [arrToReload addObject:indexPath];
    }
    }
    [self.tableView reloadRowsAtIndexPaths:arrToReload withRowAnimation:UITableViewRowAnimationNone];
    }
    //当cell移除界面的时候停止当前正在下载图片
  • (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    TableViewCell *tableViewCell = (TableViewCell *)cell;
    [tableViewCell.iconView sd_cancelCurrentImageLoad];
    }

2.苹果官方文档也有介绍该内容LazyTableImages
(本文有参考:https://www.jianshu.com/p/9e503a81de07)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值