我有一个大约有 20 个单元格的 UITableView,每个单元格中有三个 UITextField。我没有子类化 UITableViewCell,但在设置每个单元格时,我将文本字段标记值设置为常量加上行号。因此,对于每一行,文本字段的标签都会增加一。
当我运行应用程序并在第一行中输入一个值时,它可能会重新出现在第 12 行。每次运行应用程序时,行为都不相同。
我应该补充一点,我有一个数组存储每个文本字段中输入的内容。编辑文本字段时,我将新值保存到数组中,当表视图再次请求单元格时,我将文本字段值设置为存储在数组中的值。
这与重用 UITableViewCells 有关系吗?
重复使用单元格时,不同行中的文本字段可以获得相同的标签号吗?例如,第 12 行重复使用第一个单元格(文本字段标记 = 1001),那么我们有两个具有相同标记号的文本字段。如果我在第 1 行输入一个值,然后加载第 12 行,则单元格 1 中的值将从数组中加载并放入第 12 行。
如果发生这种情况,我该如何解决?
每个单元格都没有对文本字段的引用,因此我认为我无法通过访问文本字段所在的单元格来编辑文本字段的标签值。
EDIT:
这是 UITableView:cellForRowAtIndexPath 的代码:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
//Modify cell, adding textfield with row-unique index value
cell = [self modifyCellForHoleInfo:cell atIndexPath:indexPath];
}
cell.accessoryType = UITableViewCellAccessoryNone;
// Load value for textfield stored in dataArray
((UITextField *)[cell viewWithTag:1000+indexPath.row]).text = [dataArray objectAtIndex:indexPath.row];
Thanks!
问题是当电池被重复使用时(即dequeueReusableCellWithIdentifier
返回非零),单元格与现有的一起返回UITextView
。为了保持标签的唯一性,最好删除任何以前的标签UITextField
:
- (void)removeExistingTextSubviews:(UITableViewCell *)cell
{
NSMutableArray *toRemove = [NSMutableArray array];
// I don't know if you have non-TextField subviews
for (id view in [cell subviews]) {
if ([view isKindOfClass:[UITextField class]] && view.tag >= 1000) {
[toRemove insert:view];
}
}
for (id view in toRemove) {
[toRemove removeFromSuperView];
}
}
...
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
} else {
[self removeExistingTextSubviews:cell];
}
//Modify cell, adding textfield with row-unique index value
cell = [self modifyCellForHoleInfo:cell atIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryNone;
// Load value for textfield stored in dataArray
((UITextField *)[cell viewWithTag:1000+indexPath.row]).text = [dataArray objectAtIndex:indexPath.row];
请注意,我尚未编译代码,但它应该作为一个起点。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)