HASSAN MASOOD HASSAN MASOOD - 6 months ago 11
iOS Question

UiTextField creating mess with data when using in UitableView.

I have created a simple UITableViewCell with just one textField . I have given it the 1000 tag so that i can access it from my cellForRowAtIndexPath , I have also preloaded the array with some data like

- (void)viewDidLoad {
[super viewDidLoad];
_data = [[NSMutableArray alloc] init];
[_data addObject:@"Hassan"];
[_data addObject:@"Malik"];
[_data addObject:@""];
[_data addObject:@"dsldjsd"];
[_data addObject:@""];
[_data addObject:@"Halsda"];
[_data addObject:@"Hjdaslk"];[_data addObject:@"Hdjskldj"];
[_data addObject:@""];
[_data addObject:@"dsalkdmsalkn"];
[_data addObject:@""];
[_data addObject:@"jdopecnl"];
[_data addObject:@"Hassan"];
[_data addObject:@"sdsdklsmlfmf"];
[_data addObject:@""];
[_data addObject:@""];[_data addObject:@"sdnsad"];
[_data addObject:@"nsadn"];
[_data addObject:@"dlsadn"];
[_data addObject:@"sdslakdn"];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
NSLog(@"%ld",(long)indexPath.row);
NSLog(@"%@",[_data objectAtIndex:indexPath.row]);
UITextField * field = (UITextField*)[cell viewWithTag:1000];
if([[_data objectAtIndex:indexPath.row] length]>0)
{
[field setText:[_data objectAtIndex:indexPath.row]];
}
return cell;
}


when the view runs for the first time , textfields initializes with the string in the array , but when i scroll down the TableView and then go up all the entries messed up and data shuffles across the textfield.
The image below is the uitableview scene without scrollingenter image description here

but when i scroll it down and then scroll up the condition of my tableView is like
enter image description here

I have also made the custom UItableViewCell Class and make iboutlet for Textfield but result is same . Please suggest me the best solution

Answer
- (UITableViewCell *)tableView:(UITableView *)tableView    cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    NSLog(@"%ld",(long)indexPath.row);
    NSLog(@"%@",[_data objectAtIndex:indexPath.row]);
    UITextField * field = (UITextField*)[cell viewWithTag:1000];
    field.text = @"";
    if([[_data objectAtIndex:indexPath.row] length]>0)
    {
        [field setText:[_data objectAtIndex:indexPath.row]];
    } 
    return cell;
}

You have to reset text field text every time.