2011-04-06 103 views
51

我知道這可能聽起來像一個愚蠢的問題,但我已經看過每一個地方。我怎樣才能做到這一點?用動畫添加/刪除UITableViewCell?

我知道如何使用swype刪除方法來做到這一點,但我如何在該功能之外做到這一點?

請張貼一些代碼示例。

謝謝!
Coulton

回答

112
[self.tableView beginUpdates]; 
[self.tableView insertRowsAtIndexPaths:insertIndexPaths withRowAnimation:UITableViewRowAnimationFade]; 
[self.tableView deleteRowsAtIndexPaths:deleteIndexPaths withRowAnimation:UITableViewRowAnimationFade]; 
[self.tableView endUpdates]; 

insertIndexPaths是要插入到表中的NSIndexPaths的數組。

deleteIndexPaths是要從表中刪除的NSIndexPath的數組。

爲索引路徑實施例陣列格式:

NSArray *insertIndexPaths = [[NSArray alloc] initWithObjects: 
     [NSIndexPath indexPathForRow:0 inSection:0], 
     [NSIndexPath indexPathForRow:1 inSection:0], 
     [NSIndexPath indexPathForRow:2 inSection:0], 
     nil]; 
+0

感謝您的回答!我用你的方法是這樣的:'\t \t NSArray * insertIndexPaths = [[NSArray alloc] initWithObjects:[NSIndexPath indexPathForRow:0 inSection:0],nil]; \t \t \t \t [theTableView beginUpdates]; \t \t [theTableView deleteRowsAtIndexPaths:insertIndexPaths withRowAnimation:UITableViewRowAnimationLeft]; \t \t [theTableView endUpdates];'但它仍然沒有。我認爲這與'theTableView'部分有關。當嘗試'self.tableView'時,它告訴我它不是一個結構或工會......謝謝! – iosfreak 2011-04-07 03:29:33

+0

您的視圖控制器需要繼承UITableViewController,或者它只是一個UIViewController,它需要實現UITableViewDelegate和UITableViewDataSource協議。然後在界面構建器中,爲您的視圖添加一個表視圖,並將其委託和數據源屬性鏈接到您的視圖控制器。 – Sabobin 2011-04-07 09:38:41

+0

我有我的UIViewController與UITableViewDelegate和數據源(我有他們鏈接到我的UITableView在我看來)的子類。我還能做什麼錯? – iosfreak 2011-04-07 21:05:53

4

你想要這兩種方法:insertRowsAtIndexPaths:withRowAnimation:deleteSections:withRowAnimation:他們都在UITableView documentation詳細。

+0

感謝您的答覆。這是我在做什麼:'\t \t \t [processList removeObjectAtIndex:0]; \t \t \t [theTableView beginUpdates]; \t \t \t [theTableView deleteRowsAtIndexPaths:0 withRowAnimation:UITableViewRowAnimationFade]; \t \t \t [theTableView deleteSections:0 withRowAnimation:UITableViewRowAnimationFade]; \t \t \t [theTableView endUpdates];'然而沒有任何反應。 – iosfreak 2011-04-06 02:07:49

7

在夫特2.1+

tableView.beginUpdates() 
tableView.deleteRowsAtIndexPaths([YourIndexPathYouWantToDeleteFrom], withRowAnimation: .Fade) 
tableView.insertRowsAtIndexPaths([YourIndexPathYouWantToInsertTo], withRowAnimation: .Fade) 
tableView.endUpdates() 

而且可以很容易地創建一個NSIndexPath像這樣:

NSIndexPath(forRow: 0, inSection: 0)