主要利用SDImageCache的缓存的机制,在- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath;代理方法中从缓存中读取图片计算图片实际显示的高度。代码如下:
- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
if(indexPath.row==0) {
return205+239*(kScreenWidth/250);
}
if(indexPath.row==1) {
return300;
}
// 先从缓存中查找图片
NSArray * imageArray = self.productDetailModel.ProductDetail;
UIImage*image = [[SDImageCachesharedImageCache]imageFromDiskCacheForKey:imageArray[indexPath.row-2]];
// 没有找到已下载的图片就使用默认的占位图,当然高度也是默认的高度了,除了高度不固定的文字部分。
if(!image) {
image = [UIImageimageNamed:@"defaultImageH"];
}
//手动计算cell
CGFloat imgHeight = image.size.height * [UIScreen mainScreen].bounds.size.width / image.size.width;
returnimgHeight;
}
//加载图片
- (void)configureCell:(ProductImageViewCell*)cell atIndexPath:(NSIndexPath*)indexPath {
NSArray * imageArray = self.productDetailModel.ProductDetail;
NSString*imgURL = imageArray[indexPath.row-2];
UIImage *cachedImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:imgURL];
if( !cachedImage ) {
[selfdownloadImage:imgURLforIndexPath:indexPath];
[cell.urlImageViewsetImage:[UIImageimageNamed:@"defaultImageH"]];
}else{
[cell.urlImageViewsetImage:cachedImage];
}
}
/**
下载图片
@param imageURL imageURL
@param indexPath indexPath
*/
- (void)downloadImage:(NSString*)imageURL forIndexPath:(NSIndexPath*)indexPath {
// 利用 SDWebImage 框架提供的功能下载图片
[[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:imageURL] options:SDWebImageDownloaderUseNSURLCache progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
}completed:^(UIImage*_Nullableimage,NSData*_Nullabledata,NSError*_Nullableerror,BOOLfinished) {
[[SDImageCache sharedImageCache] storeImage:image forKey:imageURL toDisk:YES completion:^{
}];
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableViewreloadData];
});
}];
}
感谢网上各位大神的分享!!!!!
网友评论