我真的被这个问题困住了,看起来很奇怪,我希望有人能够看到这个问题!
我有一个 tableview Controller ,我从一组字典中填充它。每个单元格都有一个标签和一个文本字段。用户在文本字段中输入一个值,然后按下保存按钮。此时,代码遍历 TableView ,并将输入的值存储到 plist 文件中。
直到表格中有 6 行或更多行...
填充单元格的代码
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier = @"NewParamCell";
NewParameterSetCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
int row = [indexPath row];
NSDictionary *thisParam = [_AllowedParams objectAtIndex:row];
cell.ParameterLabel.text = [thisParam objectForKey:@"parameter"];
cell.ParameterUnit.text = [thisParam objectForKey:@"unit"];
return cell;
}
处理保存 Action 的代码是:
NSMutableDictionary *ContainerDict = [[NSMutableDictionary alloc] init];
// loop over table cells
for (int section = 0; section < [self.tableView numberOfSections]; section++) {
for (int row = 0; row < [self.tableView numberOfRowsInSection:section]; row++) {
NSIndexPath* cellPath = [NSIndexPath indexPathForRow:row inSection:section];
NewParameterSetCell* cell = (NewParameterSetCell *)[self.tableView cellForRowAtIndexPath:cellPath];
NSMutableDictionary *CurrentParam = [[NSMutableDictionary alloc] init];
[CurrentParam setObject:cell.ParameterLabel.text forKey:@"parameter"];
[CurrentParam setObject:cell.ParameterUnit.text forKey:@"unit"];
[CurrentParam setObject:cell.ParameterReading.text forKey:@"reading"];
[ContainerDict setObject:CurrentParam forKey:cell.ParameterLabel.text];
}
}
对于 1 - 5 行的表格,此代码可以完美运行,但一旦有 6 行或更多行,代码就无法将单元格映射到位置 0,
NewParameterSetCell* cell = (NewParameterSetCell *)[self.tableView cellForRowAtIndexPath:cellPath];
这将返回 nil,但仅针对第一次迭代,即位置 0。如果我在它周围放置一个 try catch,代码将继续,但我只得到保存到 plist 的 6 个值中的 5 个。
这让我非常抓狂,如果有人知道哪里出了问题,我将永远感激不尽!
最佳答案
这是因为 tableView 回收了单元格,所以当表格增长时,第 0 行的单元格不再存在(表格 View 已经回收它并将其用于第 6 个项目)。
与其尝试设置所有单元格(不存在)的属性,不如尝试只为将要显示的单元格设置它们。为此,您可以使用 UITableViewDataSource 并实现此方法 tableView:cellForRowAtIndexPath:
编辑:
根据您要支持的 iOS 版本,这里是方法实现的示例:
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"identifier"];
if (!cell) {
cell = [[NewParameterSetCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:@"identifier"];
}
// Configure the cell here based on indexPath …
return cell;
}
关于ios - UITableView,中断超过 6 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24642589/