2014-12-05 64 views
0

我在這裏看到很多帖子,但似乎沒有任何工作。我正在嘗試更新故事板中設置的自定義UITableViewCell標籤。我使用這個代碼時,我在下載過程中收到更新通知:UITableViewCell標籤沒有更新

NSIndexPath *index = [self.fetchedResultsController indexPathForObject:MyObject]; 
MyListTableViewCell *cell = (MyListTableViewCell *)[self.tableView cellForRowAtIndexPath:index]; 
//get the update value then 
cell.bottomLabel.text = [NSString stringWithFormat:@"%.1f MB of %.1f MB", megaBytesDownloaded, totalDownloadEstimate]; 

我可以看到記錄的值是正確的,我在更新行斷點正好擊中時,它應該是,但標籤只有在我與單元進行交互時纔會更新,或者由於某種原因,在我的下載過程完成後幾秒鐘纔會更新。

我正在使用AFNetworking,並且我所有的IBOutlets都被一次又一次地檢查過。

如何實時更新單元格?

+1

這聽起來像一種行爲,你會看到,如果你的代碼是不是主/ UI線程 – CSmith 2014-12-05 18:32:25

+0

上運行聽起來像是你不重裝的tableview 。 – 2014-12-05 18:33:46

+0

(你不應該直接更新tableview單元格,總是更新dataSource然後重新加載單元格。) – 2014-12-05 18:34:47

回答

2

您正在調用cellForRowAtIndexPath以外的tableView重載。這將給你一個重用的單元格或一個全新的實例,但不會顯示在屏幕上的單元格。

你應該做的是調用reloadRowsAtIndexPaths:withRowAnimation.

你的代碼應該有更新,你正在試圖更新單元格的bottomLabel數據源。

那麼你的代碼應該是這個樣子:

self.dataSource.megaBytesDownloaded = megaBytesDownloaded; 
self.dataSource.totalDownloadEstimate = totalDownloadEstimate; 

NSIndexPath *index = [self.fetchedResultsController indexPathForObject:MyObject]; 
[self.tableView reloadRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationNone]; 

,然後在cellForRowAtIndexPath:方法,你可以在這一點上更新您單元的bottomLabel。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    //Your normal setup code here 
    cell.bottomLabel.text = [NSString stringWithFormat:@"%.1f MB of %.1f MB", self.dataSource.megaBytesDownloaded, self.dataSource.totalDownloadEstimate]; 
} 

因爲它看起來像您還使用AFNetworking觀察下載進度,你也應該考慮在主線程中拋出您的視圖更新代碼。 AFNetworking在這種情況下使用多線程來防止UI中的任何跳轉或滯後。我建議使用GCD來允許主線程處理更新你的UI代碼。

它應該是這個樣子:

dispatch_async(dispatch_get_main_queue(), ^{ 
    //view update code here. 
}); 
+0

你在第一個答案中有。即使使用reloadRows,我也必須將它分派給主線程。標籤立即更新。我不明白,AFNetworking?它如何保持後臺線程上的單元更新? – Siriss 2014-12-05 22:18:24

+0

我會更新我的答案,將兩個答案都放在一個答案中。 AFNetworking在後臺線程上執行它們的下載更新,以防止阻止視圖線程(主線程)。通過這樣做,它可以讓您觀察下載過程而不會導致UI中的跳轉。 – 2014-12-08 18:57:45

0

我不認爲以你所做的方式訪問單元是個好主意。我建議這個

- (UITableViewCell的*)的tableView:(UITableView的*)的tableView的cellForRowAtIndexPath:(NSIndexPath *)indexPath有下面這行

cell.bottomLabel.text = [NSString stringWithFormat:@"%.1f MB of %.1f MB", megaBytesDownloaded, totalDownloadEstimate]; 

後NSIndexPath *指數= [self.fetchedResultsController indexPathForObject:爲MyObject];加入這行代碼

[self.tableView reloadRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationNone; 

希望這有助於

+0

沒有工作。顯然,它是在背景下更新的。只要我把我的cell.bottomLabel.text =放在主線程上,它就可以工作。即使調用reloadRows,我仍然不得不使用cellForRowAtIndexPath中的主線程。我不明白。 – Siriss 2014-12-05 22:17:31

0

我會嘗試使用:

- (void)reloadRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation 

而是直接分配值表格單元格。