UITableViewCell图片高度自适应问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ws_752958369/article/details/84106681

  对于一般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;
}

猜你喜欢

转载自blog.csdn.net/ws_752958369/article/details/84106681