2012-08-07 74 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並轉到屬性檢查,並檢查「剪輯子視圖」

確保您有圖像的大小設置限制。