7

将图像从 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;

}

我试过设置内容模式(尝试了aspectfill和aspect fit),尝试重置框架,设置autoresizingmask,clipTobound。没有任何改变。

4

3 回答 3

22

查看 Apple 示例项目“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;
于 2012-08-07T14:10:29.780 回答
1

我遇到了同样的问题,这对我来说非常有效;

选择 UIImage 并转到属性检查器并检查“剪辑子视图”

确保您为图像的大小设置了约束。

于 2014-12-06T17:37:17.247 回答
1

当我错误地使用单元格的 imageView 属性而不是我在情节提要中创建的自定义 UIImageView 的属性时,我遇到了这个问题。当我使用对自定义视图的正确引用时,一切都按预期工作。我怀疑你们中的一些人可能做过类似的事情。

于 2018-04-05T20:41:38.140 回答