2011-04-06 102 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)