我是iOS开发的新手,我在尝试一些应该很容易的事情时度过了一段艰难的时光.每次用户单击其中一个现有行时,在TableView中添加一行.这个动作没有真正的目的,我只是想了解TableView的行为.
所以我做了以下事情:
我使用了基于Split View的模板,并在RootViewController中将行数更改为30.
- (NSInteger)tableView:(UITableView *)aTableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return 30;
}
Run Code Online (Sandbox Code Playgroud)
方法tableView:didSelectRowAtIndexPath以下列方式查找:
- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
/*
When a row is selected, set the detail view controller's detail item to the item associated with the selected row.
*/
NSMutableArray* paths = [[NSMutableArray alloc] init];
NSIndexPath *indice = [NSIndexPath indexPathForRow:30 inSection:0];
[paths addObject:indice];
detailViewController.detailItem = [NSString stringWithFormat:@"Second Story Element %d with all its information and bla bla bla", indexPath.row];
[[self tableView] beginUpdates];
[self.tableView insertRowsAtIndexPaths:(NSArray *) paths withRowAnimation:UITableViewRowAnimationNone];
[[self tableView] endUpdates];
}
Run Code Online (Sandbox Code Playgroud)
当我执行该程序并单击其中一个元素时,我收到以下错误:
***由于未捕获的异常'NSInternalInconsistencyException'而终止应用程序,原因:'无效更新:第0节中的行数无效.更新后的现有部分中包含的行数(30)必须等于行数在更新(30)之前包含在该部分中,加上或减去从该部分插入或删除的行数(插入1个,删除0个).
我没有更改模板提供的代码的任何其他部分.
我非常详细地阅读了Apple的文档以及对以下问题的回答: 在iphone的TableView中动态添加一行 以及 如何正确使用insertRowsAtIndexPaths?
第二个问题似乎解决了同样的问题,但我无法理解正在发生的事情.他们对dataSource有什么意义?我理解的反应更好地说明如下:
这是一个两步过程:首先更新数据源,以便numberOfRowsInSection和cellForRowAtIndexPath将返回插入后数据的正确值.您必须在插入或删除行之前执行此操作,否则您将看到"无效行数"错误.
这次数据源更新意味着什么?
示例代码将非常感激,因为我完全感到沮丧.
顺便说一句,我尝试的一切都与进入编辑模式无关,是吗?
tra*_*per 14
您需要保持tableView:numberOfRowsInSection:同步返回的计数!
因此,当您有30行然后告诉tableview插入新行时,您需要确保tableView:numberOfRowsInSection:现在返回31.
- (NSInteger)tableView:(UITableView *)aTableView numberOfRowsInSection:(NSInteger)section
{
return self.rowCount;
}
- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
self.rowCount++;
[self.tableView beginUpdates];
[self.tableView insertRowsAtIndexPaths:(NSArray *) paths withRowAnimation:UITableViewRowAnimationNone];
[self.tableView endUpdates];
}
Run Code Online (Sandbox Code Playgroud)
在实践中,您可能会使用数组来跟踪您的行return [self.rows count];等
| 归档时间: |
|
| 查看次数: |
16050 次 |
| 最近记录: |