从URL加载UIImage时,在UITableViewCell中设置UIImageView Size?

Aug*_*gie 7 scale uitableview uiimageview uiimage ios

将图像从URL加载到uiimage中,然后将这些图像添加到uitableviewcell uiimageview,如下面的代码.我不知道图像大小,但需要在tableviewcell图像中强制它们为40x40.图像在uitableview中以不同的宽度加载.

阅读与uiimage尺寸/缩放相关的其他帖子,但这些解决方案对我不起作用.我在想这是因为我正在使用uitableviewcell中包含的uiimageview来创建我自己的uiimageview.

这是代码>

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

UITableViewCell *cell = [[UITableViewCell alloc] init];

ItemForSale *item = [listOfItems objectAtIndex:indexPath.row];
cell.textLabel.text = item.name;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.textLabel.font = [UIFont systemFontOfSize:14];

NSURL *url = [NSURL URLWithString: item.imgPath];
UIImage *thumbnail = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
if (thumbnail == nil) {
    thumbnail = [UIImage imageNamed:@"noimage.png"] ;
}
cell.imageView.image = thumbnail;
cell.imageView.contentMode = UIViewContentModeScaleAspectFill;
cell.imageView.frame = CGRectMake(0, 0, 40, 40);
cell.imageView.autoresizingMask = UIViewAutoresizingNone;
cell.imageView.clipsToBounds = YES;

return cell;

}
Run Code Online (Sandbox Code Playgroud)

我尝试过设置内容模式(尝试了aspectfill和aspect fit),尝试重置框架,设置autoresizingmask,clipTobound.没有一件事改变了.

Aug*_*gie 22

找到苹果示例项目"LazyTableImages"的答案

NSURL *url = [NSURL URLWithString: item.imgPath];
UIImage *thumbnail = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
if (thumbnail == nil) {
    thumbnail = [UIImage imageNamed:@"noimage.png"] ;
}
CGSize itemSize = CGSizeMake(40, 40);
UIGraphicsBeginImageContext(itemSize);
CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
[thumbnail drawInRect:imageRect];
cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

return cell;
Run Code Online (Sandbox Code Playgroud)