views:

68

answers:

1

I'm aware that to preserve memory usage, UITableViewCells are reused when scrolling. I have some custom UITableViewCells that have UITextFields in them. After text is inputted to the UITextField, and I scroll, that text is lost because of the cell reuse.

How can I make this text persist through scrolls? I'm thinking I can store each cell's text in its own index of an NSMutableArray. Then, when the cell is reused, I can repopulate it with the array data.

How would I go about doing this? Would someone be so kind as to post a code sample?

A: 

sample.h

@interface sample : UIViewController {

}

@end

sample.m

-(void)viewWillAppear:(BOOL)animated {

arrData = [[NSMutableArray alloc]init];
for (int i=0; i<10; i++) // 10- number of fields
[arrData addObject:@""];

}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; }

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

return [arrData count];

}

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

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

 cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
 cell.selectionStyle = UITableViewCellSelectionStyleNone;
 UITextField *txt = [[UITextField alloc]initWithFrame:frm];
 txt.autocorrectionType = UITextAutocorrectionTypeNo;
 txt.tag = indexPath.row;
 txt.delegate = self;
 txt.text = [arrData objectAtIndex:indexPath.row];

 [cell addSubview:txt];
 [txt release];

return cell;

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

}

-(BOOL)textFieldShouldReturn:(UITextField *)textField { [arrData replaceObjectAtIndex:[textField tag] withObject:textField.text]; }

Reena
You should check if (cell==nil)before allocationand textfield's text should be set outside the condition. To get the proper textfield's reference either you can use [cell subviews] and find the textfield with its unique 'tag' (set tag of textfield when you allocate it) or you can subclass UITableViewCell and add UITextField in its data members.
Sanniv
Thank you so much for your help. I will implement this, and let you know how it goes.
Brian Reading