views:

768

answers:

2

I added several cells to a tableview and each cell has a textField in the right to let users input texts. I find that when I scroll down and go back, the input of the first few lines will disappear. Does anybody know what's the problem?

The following is a piece of my codes:

-(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{...} }
+1  A: 

I believe that when a cell leaves the screen (due to scrolling) the iPhone immediately releases it to save memory (thus loosing the user input). Now when you scroll back up, it creates a new cell with a new UITextField in the old position with

[self CreateTextField];

You have to store the user input for each text field separately. For example, you could become the text field's delegate and catch

- (BOOL)resignFirstResponder

to be notified when the user leaves the text field focus. At this point you can assume that the user is finished with this particular field and store it.

Hauke
+3  A: 

You mean the user input will disappear? If so this is probably because cellForRowAtIndexPath: reuses the cell and will execute the [self CreateTextField] again.

So, unless you store the user input before the cell disappears, your cells will be redrawn empty and reinitialized empty.

If you do store the user input, you could reinitialize the cell with the right user input.

MiRAGe
How can I avoid to let the user recreate the textfield?
iPhoney
when input is inserted in the textfield (or when the cell will disappear) you could store the user input in an array, with the row number as index. when the cell is created (in your current code), you could check if there is an array entry with the row number as index. if there is, initialize the textfield with the stored text, if there is not initialize an empty field.
MiRAGe
thanks MiRAGe... this helped a lot!
iWasRobbed