tableViewCell 自适应图片高度 iOS

平时做tableViewCell的 自适应高的时候是给cell上的控件做好上下约束就好了,但是cell如果是纯图片的话,只是做好上下的约束是不够的。而是需要获取图片本身的高度然后赋值给cell的height。

cell上的图片大多都是网络加载的,如果后台返回每个图片对应的高度,那我们直接拿过来使用即可以。但是如果只返回图片的话,需要我们自己获取它的高。我这里使用的是SDWebImage 加载图片,在加载完图片之后会返回image,这时候就可以获取他的宽高了。

主要示例代码:
自定义cell 中
block给controller 返值

typedef void(^GetImageHeight)(CGFloat height);
@property (nonatomic, copy) GetImageHeight getImageHeight;
- (void)setImgStr:(NSString *)imgStr{
    [_imgV sd_setImageWithURL:[NSURL URLWithString:kGoodsImageUrl(imgStr)] placeholderImage:nil completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        if (image.size.height>0) {
            CGFloat scale =  (kScreenWidth-20)/image.size.width;
            CGFloat scaleHeight = image.size.height*scale;
            //返回高度给controller
            self.getImageHeight(scaleHeight);
        }
    }];
}

controller 中
先定义一个存储图片的高度的字典

@property (nonatomic, strong) NSMutableDictionary *imageHeightArray;

获取cell返回的图片高

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MallInfoTextCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([MallInfoTextCell class])];    
    cell.getImageHeight = ^(CGFloat height) {
        if (![[self.imageHeightArray allKeys] containsObject:@(indexPath.row)]) {
            [self.imageHeightArray setObject:@(height) forKey:@(indexPath.row)];
            [self.tableView beginUpdates];
            [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
            [self.tableView endUpdates];
        }
    };
    cell.imgStr = _infoImgArr[indexPath.row];
    return cell;
}

最后将高赋值给每个cell

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

你可能感兴趣的:(UI,项目)