Reputation: 559
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 scrolling
but when i scroll it down and then scroll up the condition of my tableView is like
I have also made the custom UItableViewCell Class and make iboutlet for Textfield but result is same . Please suggest me the best solution
Upvotes: 1
Views: 131
Reputation: 2077
- (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.
Upvotes: 4
Reputation: 506
just to modify to this:
if([[_data objectAtIndex:indexPath.row] length]>0)
{
[field setText:[_data objectAtIndex:indexPath.row]];
} else{
[field setText:@""];
}
table view cell are reusable, if you don't update it every time it shows, it will just display what it was, an 'else' will make sure it'll be updated every time
Upvotes: 2