2009-12-18 34 views
3

我在異步下載單元格圖像後更新我的UITableViewCells有一些問題。我使用自定義UITableViewCells像這樣:當懶惰的圖像完成下載時更新UITableViewCell

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    static NSString *CellIdentifier = @"productCell"; 
    MainTableViewCell *cell = (MainTableViewCell *)[self.tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    if (cell == nil) { 
     cell = [[[MainCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"productCell"] autorelease]; 
    } 
} 

我有一個類,是的UITableViewCell,然後一類是做所有的繪圖。這是蘋果公司的示例代碼「AdvancedTableViewCells」,我正在做複合。

我在我的單元格中有圖像,我使用Apple的示例代碼「LazyTableImages」異步下載圖像。這裏是應該更新單元的代表:

- (void)coverImageDidLoad:(NSIndexPath *)indexPath { 
    CoverImageAsyncLoader *coverImageAsyncLoader = [imageDownloadsInProgress objectForKey:indexPath]; 
    if (coverImageAsyncLoader != nil) { 
     MainTableViewCell *cell = (MainTableViewCell *)[self.tableView cellForRowAtIndexPath:coverImageAsyncLoader.indexPathInTableView]; 

     // Display the newly loaded image 
    if (coverImageAsyncLoader.products.coverImage != nil) { 
    cell.productCover = coverImageAsyncLoader.products.coverImage; 
    } else { 
    cell.productCover = blankCoverImage; 
    } 
    } 
} 

但是沒有任何反應。一位朋友告訴我,我無法從後臺線程更新用戶界面,但由於我通過委託進行操作,我不確定它爲什麼不更新。我曾嘗試:

[cell setNeedsDisplay]; 
[cell.contentView setNeedsDisplay]; 

,並設置電池爲:

cell = [[[MainCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"productCell"] autorelease]; 

,然後更新單元的顯示。

但沒有什麼工作:(我可以發佈更多的代碼,但後已經是有點長。

回答

3

如果你知道索引路徑的行部分,將有問題的細胞(如myCellIndexPath.sectionmyCellIndexPath.row),取看看重裝與表視圖的-reloadRowsAtIndexPaths:withRowAnimation:方法UITableView細胞

例如:

[tableView beginUpdates]; 
NSUInteger _path[2] = {myCellIndexPath.section, myCellIndexPath.row}; 
NSIndexPath *_indexPath = [[NSIndexPath alloc] initWithIndexes:_path length:2]; 
NSArray *_indexPaths = [[NSArray alloc] initWithObjects:_indexPath, nil]; 
[_indexPath release]; 
[tableView reloadRowsAtIndexPaths:_indexPaths withRowAnimation:UITableViewRowAnimationRight]; 
[_indexPaths release]; 
[tableView endUpdates]; 

由於此更新UI,你將在被上運行的方法想這主線程。

還有其他的行動畫,取決於品味(UITableViewRowAnimationFade,UITableViewRowAnimationNone等)。搜索關於UITableViewRowAnimation結構的幫助。

+0

謝謝......它的工作原理,但並不完美。它確實更新了單元格,但是如果我執行任何滾動操作或使用狀態欄滾動到頂部,則會使應用程序崩潰。還有一些隨機故障,在其中一個單元格上方插入一個新的「雙」行。而某些單元格不會更新。 – runmad

+0

您可能無法正確創建和取出單元格。基本上,不是「更新」單元,而是基於當前所有單元的數據狀態,需要考慮「計算」「cellForRow」方法中的單元。 –

+0

換句話說,'-reloadRowsAtIndexPaths:withRowAnimation:'最終會調用'-tableView:cellForRowAtIndexPath:'。確保您的單元格在此方法中正確出列(例如「唯一」),您正在更新此方法中的單元格內容或從此方法調用的方法中。 –