Text in UITableViewCell missing when scroll down

2019-04-17 10:54发布

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{...} }

3条回答
Luminary・发光体
2楼-- · 2019-04-17 11:32

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.

查看更多
劫难
3楼-- · 2019-04-17 11:39

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.

查看更多
仙女界的扛把子
4楼-- · 2019-04-17 11:45

You can use method to save user inputs:

- (void)textFieldDidEndEditing:(UITextField *)textField 

This methods called then user end editing the field. Save user inputs to array, for example.

查看更多
登录 后发表回答