Ondřej Mirtes
Ondřej Mirtes

Reputation: 5616

UITextField content gets lost when the view is scrolled off the screen

I have a custom UITableViewCell prototype containing UITextField. I am adding new cells automatically when filling the UITextField in the last section. Where there are more sections that do not fit on one screen and I add another one, it gets filled with values from the first section and the first section inputs are emptied!

Screenshots:

first step

added fourth row - it contains a!

first row is empty!

Related code:

@implementation TMNewTripPeopleViewController

@synthesize sectionsCount = _sectionsCount;
@synthesize firstCellShowed = _firstCellShowed;

- (int) sectionsCount
{
    if (_sectionsCount == 0) {
        _sectionsCount = 1;
    }
    return _sectionsCount;
}

- (IBAction)inputChanged:(id)sender {
    UITextField* input = (UITextField*) sender;
    NSIndexPath* indexPathName = [NSIndexPath indexPathForRow:0 inSection:input.tag - 1];
    UITableViewCell* cellName = [self.tableView cellForRowAtIndexPath:indexPathName];

    if (input == [cellName viewWithTag:input.tag]) {
        // last name input - add next section?
        if (input.tag == self.sectionsCount) {
            if (input.text.length > 0) {
                self.sectionsCount++;
                [self.tableView insertSections:[NSIndexSet indexSetWithIndex:self.sectionsCount - 1] withRowAnimation:UITableViewRowAnimationTop];
            }
        }
    }

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.sectionsCount;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *CellIdentifier = @"PersonName";
    if (indexPath.row % 2 == 1) {
        CellIdentifier = @"PersonEmail";
    }
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    UITextField* input = (UITextField*) [cell viewWithTag:indexPath.section + 1];
    if (indexPath.row == 0 && indexPath.section == 0 && !self.firstCellShowed) {
        [input becomeFirstResponder];
        self.firstCellShowed = YES;
    }

    [cell viewWithTag:1].tag = indexPath.section + 1;

    return cell;
}

@end

Upvotes: 0

Views: 1115

Answers (1)

logancautrell
logancautrell

Reputation: 8772

I'm not seeing tableView:willDisplayCell:forRowAtIndexPath: in your implementation. You generally set your cell's display values in this method.

When you use dequeueReusableCellWithIdentifier (and you almost always should) then your cells will be reused when the table view is scrolled. If you don't update their values in willDisplayCell then they will show whatever values they previously had before reuse (if any).

Upvotes: 1

Related Questions