ios - UITableViewCell 内的 UITextfield 文本在滚动时消失

标签 ios objective-c uitableview uitextfield

我正在像这样从我的每个自定义 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/

相关文章:

objective-c - NSNumberFormatter 只允许 4 位数字

ios - 有人可以看看我的代码并告诉我为什么我的数组 (AllNews) 在单元格内是空的吗

ios - 如何禁用 UITableViewCell 但仍与附属 View (即 UISwitch)进行交互

uitableview - 快速隐藏Tableview的静态单元格

ios - 如何在滚动表格时不滚动的 UITableViewController 中添加 float 按钮?

ios - iOS开发者身份需要备份什么?

ios - 处理组合的 react 性 cocoa 信号

objective-c - 展平一个 NSArray

Objective-C 原子属性线程安全

objective-c - 引用自身和实例变量的 block