您的解决方案感觉很奇怪。 Filipe 认为正确的做法是使用[wordsTableView reloadData],这将导致为每个可见单元格调用tableView:cellForRowAtIndexPath:。当您滚动表格时也会调用该方法,因此如果 reloadData 不起作用,您可能还会遇到数据在更改和滚动时无法正确更新的错误。在您的 clearValues 方法中,您通过调用 tableView:cellForRowAtIndexPath: 来做同样的事情。
我认为真正的问题在于您的tableView:cellForRowAtIndexPath: 实现。该方法通常有 2 个部分。首先,您创建或回收一个单元格以获取类似以下内容的引用:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease];
}
在 if 语句中通常是您应该向单元格添加子视图的唯一地方。如果dequeueReusableCellWithIdentifier: 返回一个单元格,它应该已经有子视图。
然后,在 if 语句之后,您填充或更新子视图的内容。您的原始代码的问题在于它正在填充文本字段并将其添加为子视图,假设单元格中还没有文本字段。所以你的tableView:cellForRowAtIndexPath: 应该看起来更像这样:
int textFieldTag = 100;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease];
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(158, 6, 148, 24)];
[textField setTag:textFieldTag];
[textField setDelegate:self];
[cell addSubview:textField];
[textField release];
}
UITextField *textField = [cell viewWithTag:textFieldTag];
NSString *strReplacement = [valueArray objectAtIndex:indexPath.row];
if (([strReplacement length] != 0) {
textField.text = strReplacement;
} else {
textField.placeholder = @"Add Value";
}
看起来您可能正在将 textField 的标记值设置为行号,大概这样您就可以在 UITextFieldDelegate 中使用它。这也可能导致错误,就像第 1 行的单元格被 dequeueReusableCellWithIdentifier: 回收并变成第 12 行一样,它将具有意外的标记值。即使现在没有发生,这也是一个等待发生的错误,并且很难排除故障。