iOS 加载网络图片&瀑布流&cell高度自适应

写在前面吧:
现目前是这样的:有数量不等的图片需要瀑布流显示,每张图片高宽度各有不同
初步思路:根据上述问题需求,可知,使用表视图为最佳方式
关键: 图片高宽度不定,cell需要动态计算高度;图片需做缩放处理,适应屏幕
使用SDWebImage下载图片

思路就如上所述,具体代码如下:

1、计算cell高度(前提是已做好数据请求处理)
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    // 先从缓存中查找图片
    UIImage *image = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:self.sdwebArr[indexPath.row]];
    if (!image) {
        image = [UIImage imageNamed:@"store_no_data"];
    }
    //H = H*(SCREEN_WIDTH/W) = 高度*(屏幕/图片宽)
    CGFloat imageHeight = image.size.height * SCREEN_WIDTH/image.size.width;
    return imageHeight;
}
2、cellForRowAtIndexPath(调用configureCell: atIndexPath:方法)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ShopDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (cell == nil) {
        cell = [[ShopDetailCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
    }
    [self configureCell:cell atIndexPath:indexPath];

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
3、调用(downloadImage: forIndexPath:)
- (void)configureCell:(ShopDetailCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    NSString *imgURL = self.sdwebArr[indexPath.row];
    UIImage *cachedImage = [[SDImageCache sharedImageCache]imageFromDiskCacheForKey:imgURL];
    
    if (!cachedImage) {
        [self downloadImage:self.sdwebArr[indexPath.row] forIndexPath:indexPath];

    }else{
        [cell.imgBtn setBackgroundImage:cachedImage forState:UIControlStateNormal];
    }
}
4、下载对应图片、使用GCD回到主线程刷新UI
- (void)downloadImage:(NSString *)imageURL forIndexPath:(NSIndexPath *)indexPath {
    [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:imageURL] options:SDWebImageDownloaderUseNSURLCache progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
        //nothing to do
    } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
        [[SDImageCache sharedImageCache] storeImage:image forKey:imageURL toDisk:YES completion:^{
            
        }];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.detailTableView reloadData];
        });
    }];
}

结束语:
感谢icefishlily的blog
当你以为你已经够努力时,你总会遇到更优秀的人,见到更不可思议的风景。
诸君,共勉之~

你可能感兴趣的:(iOS 加载网络图片&瀑布流&cell高度自适应)