xcode 如何在 UITableView 中插入新单元格?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14176244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I insert new cells in a UITableView?
提问by user1654889
I am trying to add a row to a tableview using
我正在尝试使用
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
It throws an exception where I call insertRowsAtIndexPaths:withRowAnimation:, which says
它抛出一个异常,我调用 insertRowsAtIndexPaths:withRowAnimation:,它说
Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
It is returning the correct number of rows and sections, but it never makes it to cellForRowAtIndexPath before throwing the exception. I am doing this with a storyboard also and I have the tableView set to have static cells because the majority of the tableView does in fact have static cells. I really don't want to switch over to dynamic prototypes because then I can't have IBOutlets and IBActions, which I am using, and I would have to essentially start over with respect to the layout of the cells. Is there any way for me to get rid of this exception without changing my tableView to have dynamic prototype cells?
它正在返回正确的行数和节数,但在抛出异常之前它永远不会到达 cellForRowAtIndexPath。我也在用故事板做这件事,并且我将 tableView 设置为具有静态单元格,因为大多数 tableView 实际上确实具有静态单元格。我真的不想切换到动态原型,因为那样我就不能拥有我正在使用的 IBOutlets 和 IBActions,而且我必须从根本上重新开始单元格的布局。有什么方法可以让我摆脱这个异常而不改变我的 tableView 以拥有动态原型单元格?
Edit
编辑
The line right before what I posted is
我发布的内容之前的那一行是
[itemsInCurrentPurchase insertObject:itemName atIndex:0];
which is supposed to update the array. I am using
这应该更新数组。我在用
[itemsInCurrentPurchase count]
for my number of rows in section and it is returning the correct number after the update. The problem is that the cellForRowAtIndexPath method is not even being reached. During the update is there anything else that gets called between the number of rows and the cell type that could be causing this error?
对于我部分中的行数,它在更新后返回正确的数字。问题是甚至没有达到 cellForRowAtIndexPath 方法。在更新期间,在行数和单元格类型之间是否还有其他可能导致此错误的调用?
回答by iDev
You need to update your data source with this new object before inserting the row. Otherwise it will crash while trying to update the table view with this new row.
在插入行之前,您需要使用这个新对象更新您的数据源。否则它会在尝试用这个新行更新表视图时崩溃。
for eg:-
例如:-
[self.dataSourceArray insertObject:object atIndex:indexPath.row];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];