2012-05-19 21 views
1

我想找到一個簡單的教程,用於在滾動時在uitableview單元上異步插入自定義對象,因爲我的uitableview不能很好地滾動。我已經搜索,但我只發現有關圖像異步加載沒有幫助。我有一個需要加載異步的uview。在對象加載之前需要進行太多的處理工作,結果滾動不平滑。任何簡單的教程來滾動時加載自定義對象在uitableview單元上異步

任何幫助表示讚賞。

+0

這裏是一個很好的問題,涵蓋這樣的:http://stackoverflow.com/q/7567827/937822 – lnafziger

回答

4

這並不像看起來那麼難。只有一個警告。即使沒有完全加載,你也必須知道你的細胞的高度。

如果tableView具有恆定的行高度,則設置tableView.rowHeight。如果您需要快速確定行高,請使用UITableViewDelegate的回調函數–tableView:heightForRowAtIndexPath:

然後在-tableView:cellForRowAtIndexPath中取出一個單元格,將其設置爲某個初始狀態,啓動一個NSOperation或GCD塊,最後返回已重置的單元格。

在NSOperation或CCG塊中,您將執行所需的工作,然後回調主線程以將值設置到單元格中。這是異步單元加載的本質。


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    // dequeue a cell 

    // Reset the cell 
    cell.imageView.image = nil; 
    cell.textLabel.text = nil; 
    cell.detailTextLabel.text = nil; 

    // Use gcd 
    dispatch_queue_t queue = dispatch_queue_create("blah blah replace me blah", 0); 
    dispatch_async(queue, ^{ 

     // Do work in the background 

     UIImage *image  = value1; 
     NSString *text  = value2; 
     NSString *detailText = value3; 

     dispatch_async(dispatch_get_main_queue(), ^{ 
      // Back to main thread to set cell properties. 
      if ([tableView indexPathForCell:cell].row == indexPath.row) { 
       cell.imageView.image  = image; 
       cell.textLabel.text  = text; 
       cell.detailTextLabel.text = detailText; 
      } 
     });//end 
    });//end 
    dispatch_release(queue); 

    // Return the reset cell 
    return cell; 
} 
+0

謝謝回答傑弗瑞。如果你能提供一個簡單的例子,我將不勝感激。 – stefanosn

+1

我添加了'-tableView:cellForRowAtIndexPath:'的GCD示例。 –

+0

謝謝!請告訴我,如果我是正確的... dispatch_async塊中的代碼將執行並在後臺完成工作,然後dispatch_async(dispatch_get_main_queue()將更新主線程上的單元格屬性。我的問題是關於return cell這段代碼會執行嗎?它會等待調度完成?這是我感到困惑的地方,因爲如果沒有等待,那麼我將得到一個沒有任何內容的單元,並且在調度完成後,我得到更新屬性當我向上或向下滾動時會發生什麼? – stefanosn

相關問題