在网上找到了一段不错的代码,笔记一下
- #pragma mark - UITableViewDelegate, UITableViewDataSource
- - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
- return 1;
- }
- - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
- return self.imgArray.count;//图片URL以数组的形式存在
- }
- - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
- // 先从缓存中查找图片
- UIImage *image = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey: self.imgArray[indexPath.row]];
- // 没有找到已下载的图片就使用默认的占位图,当然高度也是默认的高度了,除了高度不固定的文字部分。
- if (!image) {
- image = [UIImage imageNamed:kDownloadImageHolder];
- }
- //手动计算cell
- CGFloat imgHeight = image.size.height * [UIScreen mainScreen].bounds.size.width / image.size.width;
- return imgHeight;
- }
- - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
- static NSString *imgID = @"pictureCellID";
- PYClubPresentDetailImgTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:imgID];
- if (nil == cell) {
- cell = [[PYClubPresentDetailImgTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:imgID];
- }
- [self configureCell:cell atIndexPath:indexPath];
- cell.userInteractionEnabled = NO;
- return cell;
- }
- - (void)configureCell:(PYClubPresentDetailImgTableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
- NSString *imgURL = self.imgArray[indexPath.row];
- UIImage *cachedImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:imgURL];
- if ( !cachedImage ) {
- [self downloadImage:self.imgArray[indexPath.row] forIndexPath:indexPath];
- [cell.btn setBackgroundImage:[UIImage imageNamed:kDownloadImageHolder] forState:UIControlStateNormal];
- } else {
- [cell.btn setBackgroundImage:cachedImage forState:UIControlStateNormal];
- }
- }
- - (void)downloadImage:(NSString *)imageURL forIndexPath:(NSIndexPath *)indexPath {
- // 利用 SDWebImage 框架提供的功能下载图片
- [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:imageURL] options:SDWebImageDownloaderUseNSURLCache progress:^(NSInteger receivedSize, NSInteger expectedSize) {
- // do nothing
- } completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
- [[SDImageCache sharedImageCache] storeImage:image forKey:imageURL toDisk:YES];
- dispatch_async(dispatch_get_main_queue(), ^{
- [self.tableView reloadData];
- });
- }];
- }