2011-11-16 32 views
2

我正在將圖像加載到我的UITableViewCell中,並且它變得波濤洶涌。我最多隻有5-10個細胞。如何使UITableViewCell中的圖像平滑滾動?

有沒有簡單的方法可以解決這個問題?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"appointmentCell"; 

    AppointmentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    NSDictionary *appointmentDictionaryTemp = [self.appointmentArray objectAtIndex:indexPath.row]; 
    cell.patientNameLabel.text = [appointmentDictionaryTemp objectForKey:@"patient"]; 
    cell.appointmentTimeLabel.text = [appointmentDictionaryTemp objectForKey:@"scheduled_time"]; 

    NSString *urlString = [[appointmentDictionaryTemp objectForKey:@"patient_small_photo_url"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 
    NSData * imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]]; 
    UIImage * image = [UIImage imageWithData:imageData]; 
    cell.patientImage.image = image; 

    return cell; 
} 
+1

的主要問題是在[NSData的dataWithContentsOfURL:...],直至下載完成,阻止你的應用程序。對我來說,解決這個問題的簡單而快速的方法是使用AFNetworking庫:在它的網站上,你可以找到一些有用的例子來說明如何下載圖像...... –

回答

2

dataWithContentsOfURL:是你的罪魁禍首。它在應用程序的主UI線程上執行同步(阻塞)網絡請求,導致表視圖在圖像下載時鎖定。

該解決方案涉及更多,它涉及到使用NSURLConnection(或其他第三方庫)異步下載數據,從而允許UI在下載圖像時保持響應。 This是一個很好的參考資料。

0

使用索引路徑作爲關鍵字將圖像存儲在NSCache中,然後在您的 tableView:cellForRowAtIndexPath:方法中,檢查是否存在索引路徑的對象。如果有加載到圖像屬性,如果沒有,然後調用一個方法來生成它。這會在每次繪製單元格時停止它的完成。

0

有一個開放源代碼(MIT許可證)實現的UIImageView圖像的延遲/緩存網絡,你應該看看:SDWebImage。下載/緩存圖像異步並自動更新您的UIImageViews。

1

創建一個名爲imageCache的伊娃,這是一個NSArray。在cellForRowAtIndexPath

for (NSDictionary *appointmentDictionaryTemp in self.appointmentArray) {   
    NSString *urlString = [[appointmentDictionaryTemp objectForKey:@"patient_small_photo_url"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 
    NSData * imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]]; 
    UIImage * image = [UIImage imageWithData:imageData]; 

    [imageCache addObject:image]; 
} 

現在:現在init運行這段代碼

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"appointmentCell"; 

    AppointmentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    NSDictionary *appointmentDictionaryTemp = [self.appointmentArray objectAtIndex:indexPath.row]; 
    cell.patientNameLabel.text = [appointmentDictionaryTemp objectForKey:@"patient"]; 
    cell.appointmentTimeLabel.text = [appointmentDictionaryTemp objectForKey:@"scheduled_time"]; 

    cell.patientImage.image = [imageCache objectAtIndex:indexPath.row]; 

    return cell; 
}