寫(xiě)在前面吧:
現(xiàn)目前是這樣的
:有數(shù)量不等的圖片需要瀑布流顯示棕兼,每張圖片高寬度各有不同
初步思路
:根據(jù)上述問(wèn)題需求障斋,可知贞瞒,使用表視圖為最佳方式
關(guān)鍵
: 圖片高寬度不定,cell需要?jiǎng)討B(tài)計(jì)算高度摆寄;圖片需做縮放處理失暴,適應(yīng)屏幕
使用SDWebImage下載圖片
思路就如上所述,具體代碼如下:
1微饥、計(jì)算cell高度(前提是已做好數(shù)據(jù)請(qǐng)求處理)
- (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(調(diào)用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、調(diào)用(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欠橘、下載對(duì)應(yīng)圖片矩肩、使用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];
});
}];
}
結(jié)束語(yǔ):
感謝icefishlily的blog
當(dāng)你以為你已經(jīng)夠努力時(shí),你總會(huì)遇到更優(yōu)秀的人肃续,見(jiàn)到更不可思議的風(fēng)景黍檩。
諸君叉袍,共勉之~