简体   繁体   English

在UITableViewCells中维护UITextFields中的文本

[英]Maintaining text in UITextFields in UITableViewCells

My Problem: I have a UITableView section that is used to create a list. 我的问题:我有一个用于创建列表的UITableView部分。 Each TableViewCell has UITextField in it. 每个TableViewCell都包含UITextField。 When you begin typing the textfield, a new cell is inserted. 当您开始键入文本字段时,将插入一个新单元格。 All of this functionality works perfectly. 所有这些功能都非常有效。 However, if the user creates many cells, they go off screen and problems occur. 但是,如果用户创建了许多单元格,它们会离开屏幕并出现问题。 Specifically that the cells on top of the section start to get reused. 特别是该部分顶部的单元格开始被重用。 This results in unwanted text in new cells, and the deletion of text in old ones. 这会导致新单元格中出现不需要的文本,并删除旧单元格中的文本。 How might I fix this? 我该如何解决这个问题?

Images of this problem: (in the second image, as I started typing item 6, item 1 appeared below it) 这个问题 的图像:(在第二张图片中,当我开始输入第6项时,第1项出现在它下面)

在此输入图像描述

在此输入图像描述

Code to create UITableViewCells: 创建UITableViewCells的代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   static NSString *CellIdentifier = @"AddListInformationCellid";


    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {

        // Intialize TableView Cell
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                       reuseIdentifier:CellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor whiteColor];


        // Initialize TextField
         // ... code ommitted for brevity

        // Custome intializiation per each kind of TextField
        if (indexPath.section == 0) {
            playerTextField.tag = 0;
            playerTextField.placeholder = @"Title";
        }
        else if (indexPath.section == 1) {

            // Here's where the problem starts *********

            playerTextField.tag = indexPath.row + 1;
            playerTextField.placeholder = @"List Item";
        }

            [cell.contentView addSubview:playerTextField];
    }


    return cell;
}

Code to add/delete cells 用于添加/删除单元格的代码

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

    NSInteger section = [self.tableView indexPathForCell:(UITableViewCell *)textField.superview.superview].section;
    NSInteger row = [self.tableView indexPathForCell:(UITableViewCell *)textField.superview.superview].row;

    if (section == 0) {

        _myList.name = textField.text;
    }
    else if (section == 1) {

        // Delete cell that is no longer used
        if ([string isEqualToString:@""]) {
            if (textField.text.length == 1) {
                if (cellCount > 1) {
                cellCount = cellCount - 1;

                [self.tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:row inSection:1]] withRowAnimation:UITableViewRowAnimationAutomatic];

                textField.text = @"";
                }
            }
        }

        // Add a new cell
        if (self.beganEditing) {
            if (![string isEqualToString:@""]) {
            if (row == [self.tableView numberOfRowsInSection:1] - 1) {
                cellCount = cellCount + 1;
                [self.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:row + 1 inSection:1]] withRowAnimation:UITableViewRowAnimationAutomatic];
                self.beganEditing = NO;
                }
            }
        }
    }    

    return YES;
}

As @Bruno said, you need to watch what you put into the initialization of the cell. 正如@Bruno所说,你需要观察你在细胞初始化中投入的内容。 A good general rule would be to only put universal rules into the cell == nil conditional. 一个好的一般规则是只将通用规则放入cell == nil条件。 Anything that depends on the position of the cell in the table view needs to go outside this if statement. 依赖于表视图中单元格位置的任何内容都需要超出此if语句。

In the code above, you have a comment "Custom initialization per each kind of text field." 在上面的代码中,您有一条注释“每种文本字段的自定义初始化”。 That's a pretty good indicator that this code needs to go outside the if statement. 这是一个很好的指标,这个代码需要超出if语句。

Secondly, you cannot rely on the table view cells to keep your data for you . 其次, 您不能依赖表格视图单元格来保存您的数据 If you don't already have one, you need to keep an array of strings that represents each entry in the text fields area. 如果您还没有,则需要保留一个字符串数组,表示文本字段区域中的每个条目。 Then when asked for a cell by the table view, you can set each text field's text according to its index path outside the cell == nil conditional . 然后,当通过表视图询问单元格时,可以根据cell == nil 条件 之外的索引路径设置每个文本字段的文本。

Check out this answer as well. 看看这个答案

Hope this helps! 希望这可以帮助!

You bug is on the 你的bug就在

if (cell == nil)

part of your code. 部分代码。 You're not considering the else , which is the case when the cell is reused. 你不是在考虑else ,这是细胞被重复使用的情况。 (The cell is reused, that's why it's appearing on the bottom). (细胞被重复使用,这就是它出现在底部的原因)。

You should make sure that you treat the reuse case (in other words, that you configure your cell accordingly when its reused) 您应该确保处理重用案例(换句话说,在重用时相应地配置您的单元格)

I found your problem. 我找到了你的问题。 But it's a bit hard to say. 但这有点难以说。

Try to think about, when table view is going to present a cell in a row, it will choose a cell in the reuse-queue which has the same type of the one is going to be shown. 试着考虑一下,当表视图要在一行中呈现一个单元格时,它将在重用队列中选择一个与将要显示的单元格相同的单元格。 In other words, table view just knows the type of the reused-cell it choosed and the comment of the cell is recognized by which row is in! 换句话说,表视图只知道它选择的重用单元的类型,并且单元的注释被哪一行识别! So let see your code. 那么看看你的代码吧。

You can know that you only creat one cell with your text when is nil. 您可以知道,只有零时,您才会使用您的文本创建一个单元格。 However, when it is going to be used, the cell with the same type don't know which row he is in and so it don't know what kind of comment it hold and just presented with the its last infromations!! 然而,当它将被使用时,具有相同类型的单元格不知道他在哪一行,因此它不知道它持有什么样的注释并且只是呈现其最后的infromations !!

Here's the solution. 这是解决方案。 Try to save your infos in an array well-organized(Such as: you can back your info by which row its in ), basic on its rows, try to update your cell's comment by which row its in relating to the info-array. 尝试将您的信息保存在一个组织良好的数组中(例如:您可以通过其中的哪一行返回您的信息),基本在其行上,尝试更新您的单元格的注释,其中哪一行与info-array相关。

hope it can help:) 希望它可以帮助:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM