代码之家  ›  专栏  ›  技术社区  ›  Chilly Zhong

向下滚动时,UITableViewCell中的文本丢失

  •  0
  • Chilly Zhong  · 技术社区  · 16 年前

    我在TableView中添加了几个单元格,每个单元格的右侧都有一个文本字段,允许用户输入文本。我发现当我向下滚动并返回时,前几行的输入将消失。有人知道有什么问题吗?

    以下是我的代码:

    -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath
        *)indexPath
            {
                //init cell
                static NSString *TableIdentifier = @"MyIdentifier";
                UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:TableIdentifier];
                if(cell == nil) {
                    cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero 
                                            reuseIdentifier:TableIdentifier] autorelease];
                }
    
                //set cell for each row
                if([indexPath row] == 0)
                {
                    cell.textLabel.text = @"Row A";
                    txt_A = [self CreateTextField];         //create textField
                    [cell.contentView addSubview:txt_A];        //add textField to cell
                }
                else if([indexPath row] == 1)
                {
                    cell.textLabel.text = @"Row B";
                        txt_B = [self CreateTextField];
                        [cell.contentView addSubview:txt_B];
                }
                else{...} }
    
    3 回复  |  直到 14 年前
        1
  •  3
  •   Jake    16 年前

    你的意思是用户输入会消失?如果是这样,这可能是因为 cellForRowAtIndexPath: 重新使用单元格并执行 [self CreateTextField] 再一次。

    因此,除非在单元格消失之前存储用户输入,否则单元格将重新绘制为空并重新初始化为空。

    如果确实存储了用户输入,则可以使用正确的用户输入重新初始化单元格。

        2
  •  1
  •   Hauke    16 年前

    我相信当一个手机离开屏幕(由于滚动)时,iPhone会立即释放它以节省内存(从而失去用户输入)。现在,当您向上滚动时,它将在旧位置创建一个新的单元,其中新的uitextfield

    [self CreateTextField];
    

    必须分别存储每个文本字段的用户输入。例如,您可以成为文本字段的委托并捕获

    - (BOOL)resignFirstResponder
    

    当用户离开文本字段焦点时得到通知。此时,您可以假设用户已经完成了这个特定的字段并存储它。

        3
  •  1
  •   Pavel Volobuev    14 年前

    可以使用方法保存用户输入:

    - (void)textFieldDidEndEditing:(UITextField *)textField 
    

    此方法调用了用户端编辑字段。例如,将用户输入保存到数组。

    推荐文章