UITableViewCell图片高度自适应问题

  对于一般UI设计,我们都把图片的写死,但是经常有种需求是需要我们自动根据图片宽高比实现图片的自动缩放功能。这里有多种办法可以解决这种问题,常见的问题处理方式有如下几种:

1.后台返回图片的尺寸大小,然后前端根据图片size调整响应的高度,一般宽度定死。

2.利用网络图片框架,获取下载到的网络图片实际大小,然后缓存起来,局部刷新cell,重新展示。

鉴于之前项目上面也是有类似的需求,这里我们就采用了第二种方案实现:

/**缓存图片高度*/
@property (nonatomic,strong)NSMutableDictionary *imageHeightArray;

部分源码展示:

1.cellForIndexPath中缓存图片高度,并刷新

 [cell.currentImgView sd_setImageWithURL:[NSURL URLWithString:imgURL] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        if (image.size.height>0) {
            CGFloat scale =  screenWidth/image.size.width;
            CGFloat scaleHeight = image.size.height*scale;
            if (![[slf.imageHeightArray allKeys] containsObject:@(indexPath.row)]) {
                [slf.imageHeightArray setObject:@(scaleHeight) forKey:@(indexPath.row)];
                [slf.tableView beginUpdates];
                [slf.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                [slf.tableView endUpdates];
            }
        }
    }];

2.heightForRowAtIndexPath中返回实际高度

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = [[self.imageHeightArray objectForKey:@(indexPath.row)] floatValue];
    if (height>0) {
        return height;
    }
    //给定图片一个默认高度,用于临时占位图
    return 200;
}

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值