我正在像这样从我的每个自定义 UITableView 单元格中将数据存储到 NSUserDefaults 中:
for (int i = 0; i < additionalClaimants; i++)
{
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
UITableViewCell *cell = [self.table_view cellForRowAtIndexPath:indexPath];
UITextField* firstNameField = (UITextField *)[cell viewWithTag:1];
UITextField* employeeIDField = (UITextField *)[cell viewWithTag:2];
[defaults setObject:firstNameField.text forKey:[NSString stringWithFormat:@"claimant%d_name",i+1]];
[defaults setObject:employeeIDField.text forKey:[NSString stringWithFormat:@"claimant%d_employeeID",i+1]];
}
[defaults setInteger:additionalClaimants forKey:@"total_add_claimants"];
[defaults synchronize];
我在 UITableView 中显示数据,就像在 cellForIndexPath 方法中一样:
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
AdditionalClaimantsTableViewCell *cell = [self.table_view
dequeueReusableCellWithIdentifier:@"Cell"];
NSString *claimant_name = [defaults objectForKey: [NSString stringWithFormat:@"claimant%ld_name", (long)indexPath.row+1]];
NSString *claimant_employeeID = [defaults objectForKey: [NSString stringWithFormat:@"claimant%ld_employeeID", (long)indexPath.row+1]];
cell.txtField_eid.text = claimant_employeeID;
cell.txtField_name.text = claimant_name;
return cell;
}
问题是在滚动时,出现在 View 之外的文本字段似乎丢失了其中的数据。
最佳答案
您在 cellForRowAtIndexPath
中的代码没有问题(需要明确您要使用哪个版本的 dequeueReusableCellWithIdentifier
)。您的问题出在您尝试保存值的 for
循环中。如果调试此 for
循环,您会发现 cell
对于不再显示在屏幕上的任何行都是 nil。您需要找到一种方法来在每行滚动到屏幕外之前(或尽快)保存每行的值。为此,请使用 tableView 委托(delegate)方法:
- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
检查并保存该方法中的 textField 值。
您仍然需要保存所有可见单元格的值。您现有的 for 循环将实现这一点,但您可以通过使用 tableView 的 visibleCells
属性来获取单元格数组并迭代它(这将避免为不是的行构建 indexPath可见)。
关于ios - UITableViewCell 内的 UITextfield 文本在滚动时消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30291489/