2013-10-15 49 views
1

刪除與動畫一個細胞我想通過一個刪除某些細胞在動畫一個的表圖,在第一我使用這樣的代碼:的iOS的UITableView由一個

[self beginUpdates]; 
[self deleteRowsAtIndexPaths:removeIndexPaths withRowAnimation:UITableViewRowAnimationFade]; 
[self endUpdates]; 

有在removeIndexPaths陣列6個indexPaths 。它以正確的方式工作,但動畫效果爲1.六個單元格爲空,2。淡化空白區域。

然後我嘗試將其刪除了/而像這樣:

int removeIndexRow = indexPath.row + 1; 
while (item.level < nextItemInDisplay.level) 
{ 
    NSIndexPath *removeIndexPath = [NSIndexPath indexPathForRow:removeIndexRow inSection:0]; 
    [items removeObject:nextItemInDisplay]; 
    [self beginUpdates]; 
    [self deleteRowsAtIndexPaths:@[removeIndexPath] withRowAnimation:UITableViewRowAnimationFade]; 
    NSLog(@"1"); 
    sleep(1); 
    NSLog(@"2"); 
    [self endUpdates]; 
} 

爲了知道該函數是如何工作的,我使用的睡眠和的NSLog輸出的一些標誌。然後我發現結果是輸出所有的標誌後,六個單元格被關閉在一起,最不可思議的是他們的動畫是這樣的:1.五個單元格消失,沒有動畫,2.第一個單元格爲空, 3.淡出第一個單元格空白區域。

但我想要的是逐個刪除單元格,首先第一個單元格爲空並淡入淡出,然後是第二個,第三個......我該如何解決它?

回答

3

問題是你的循環(在裏面調用sleep)在UI線程上運行。直到您將UI線程的控制權返回給操作系統,UI纔會更新,以便它可以執行必要的動畫。

嘗試在不同的線程中運行此操作,並調用以在UI線程上逐個刪除單元格。代碼可能看起來像這樣:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
    // Now we're running in some thread in the background, and we can use it to 
    // manage the timing of removing each cell one by one. 
    for (int i = 0; i < 5; i++) 
    { 
     dispatch_async(dispatch_get_main_queue(), ^{ 
      // All UIKit calls should be done from the main thread. 
      // Make the call to remove the table view cell here. 
     }); 
     // Make a call to a sleep function that matches the cell removal 
     // animation duration. 
     // It's important that we're sleeping in a background thread so 
     // that we don't hold up the main thread. 
     [NSThread sleepForTimeInterval:0.25]; 
    } 
}); 
+0

謝謝,我試過了,就像你說的。如果我將間隔設置爲1秒,它會逐個消失,這是正確的。但是,如果我將間隔設置爲0.25秒,就會像第二種情況一樣工作。 – pingshw

+0

這是正確的 - 因爲'sleep'函數需要整數秒的時間。通過0.25將下降到0,不會有任何延遲。相反,試試這個:'[NSThread sleepForTimeInterval:0.25];'。我編輯了答案來反映這一點。 –

+0

而不是睡覺這個看起來總是令人懷疑的線程,你可以通過使用GCD的'dispatch_after()'函數來錯開要移除的線程,這個函數還有一個額外的好處,就是不需要創建一個背景隊列,可以直接放到主隊列中。 – Abizern

相關問題