Isa*_* T. 5 iphone cocoa-touch objective-c uitableview
我有一个大约20个单元格的UITableView,每个单元格中有三个UITextFields.我没有子类UITableViewCell,但在设置每个单元格时,我将textfields标记值设置为常量加上行号.因此,对于每一行,文本字段的标记都加1.
当我运行应用程序并在例如第一行中输入值时,它可能会重新出现在第12行.每次运行应用程序时行为都不一样.
我应该补充一点,我有一个数组存储在每个文本字段中输入的内容.编辑文本字段时,我将新值保存到数组中,当tableview再次请求单元格时,我将textfields值设置为存储在数组中的值.
这与重用UITableViewCells有关吗?重用单元格时,不同行中的文本字段是否可以获得相同的标记号?比如说第一个单元格(textfield tag = 1001)在第12行重用,然后我们有两个具有相同标签号的文本字段.如果我然后在第1行输入值并稍后加载第12行,则第1个单元格中的值将从数组中加载并放入第12行.
如果发生这种情况,我该如何解决?每个单元格都没有对文本字段的引用,所以我不认为我可以通过访问它所在的单元格来编辑文本字段的标记值.
编辑:
以下是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];
Run Code Online (Sandbox Code Playgroud)
谢谢!
问题是当重用单元格(即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];
Run Code Online (Sandbox Code Playgroud)
请注意,我没有编译代码,但它应该作为一个起点.
| 归档时间: |
|
| 查看次数: |
2055 次 |
| 最近记录: |