2012-08-07 72 views
7

将URL中的图像加载到uiimage中,然后将这些图像添加到uitableviewcell uiimageview中,如下面的代码。我不知道图像大小,但需要强制它们在tableviewcell图像中为40x40。图像在uitableview中以不同的宽度持续加载。当UIImage从URL加载时,在UITableViewCell中设置UIImageView大小?

通读其他与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和方面配合),试图复位帧,设定autoresizingmask,clipTobound。没有一件事改变了一件事。

+0

我只是试图用一个自定义的uiimageview,它工作正常。必须是在uitableviewcell中包含的uimageview的东西 – Augie 2012-08-07 13:58:41

回答

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; 
+0

我试过了,但是收到一条消息“你必须等待2天才能接受你自己的答案”。 – Augie 2012-08-07 17:32:18

+0

你必须把这个信息放在哪一类的信息中?这是在你的UITableView或UITableViewCell的子类中吗? – 2012-08-23 13:53:56

+1

上面的代码在主线程'tableView:cellForRowAtIndexPath:'中,但后来我切换我的代码以模仿苹果dev站点上的'lazy table images'中的示例,该示例从'tableView:cellForRowAtIndexPath: '然后下载图像,将其保存为uiimage,并在完成后,将uiimage返回到主线程以放入cell.imageView。我认为icondownloader是在示例项目中在后台运行的对象的名称。 – Augie 2012-08-23 14:22:03

1

我有同样的问题,这个工作非常适合我;

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

确保您有图像的大小设置限制。