主要利用SDImageCache的緩存的機(jī)制,在- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath;代理方法中從緩存中讀取圖片計(jì)算圖片實(shí)際顯示的高度皂吮。代碼如下:
- (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]];
? ? // 沒有找到已下載的圖片就使用默認(rèn)的占位圖,當(dāng)然高度也是默認(rèn)的高度了,除了高度不固定的文字部分夕春。
? ? if(!image) {
? ? ? ? image = [UIImageimageNamed:@"defaultImageH"];
? ? }
? ? //手動(dòng)計(jì)算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];
? ? ? ? });
? ? }];
}
感謝網(wǎng)上各位大神的分享I稹1芘亍Q髦ァT叽骸蜂厅!