Mr.Boy
Mr.Boy

Reputation: 3

ios textfield inside tableview cell

I have created 2 textfields inside 2 cells.

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell;
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    if (indexPath.row == 0) {
        [self CustomTextField:cell :txtFirstName];
        txtFirstName.text = [_dictInfoOneUser objectForKey:@"firstname"];
        [cell addSubview:txtFirstName];
        txtFirstName.tag = 100;
    }
    else (indexPath.row == 1){
        [self CustomTextField:cell :txtLastName];
        txtLastName.text = [_dictInfoOneUser objectForKey:@"lastname"];
        [cell addSubview:txtLastName];
        txtLastName.tag = 101;
    }
}

I think I set txtFirstName.text = [_dictInfoOneUser objectForKey:@"firstname"];. I edited cell firstname, after that, I scroll, it's refresh cell and reset my edited in textfield.

how to I can resolve this problem.

************ Edited

-(void)CustomTextField :(UITableViewCell *)cell :(UITextField *)textField{
    //add bottom border
    CALayer *border = [CALayer layer];
    border.borderColor = [UIColor grayColor].CGColor;
    border.frame = CGRectMake(cell.frame.size.width / 2 - 160, textField.frame.size.height - 1, textField.frame.size.width, textField.frame.size.height);
    border.borderWidth = 1;
    [textField.layer addSublayer:border];
    textField.layer.masksToBounds = YES;
    [textField setTextAlignment:NSTextAlignmentCenter];
}

Upvotes: 0

Views: 659

Answers (2)

Champoul
Champoul

Reputation: 1004

It seems that you're not dequeing your cell in the first place, here's what your

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

should look like :

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
...
}

Upvotes: 1

danh
danh

Reputation: 62686

This is due to cell reuse. The pattern to follow is to conditionally build the subviews (so you get only one per cell), but unconditionally configure them. Like this...

if (indexPath.row == 0) {
    UITextField *txtFirstName = (UITextField *)[cell viewWithTag:100];
    if (!txtFirstName) {
        // it doesn't exist. build it
        [self CustomTextField:cell :txtFirstName];  // not sure what this does, assuming it's part of building it
        [cell addSubview:txtFirstName];
        txtFirstName.tag = 100;
    }
    // whether it was just built or not, give it a value
    txtFirstName.text = [_dictInfoOneUser objectForKey:@"firstname"];
}
// same idea for the other row/textfield

Upvotes: 0

Related Questions