开发者

iPhone SDK: Making UITextField text in a custom UITableViewCell persist through scrolls?

开发者 https://www.devze.com 2023-01-06 23:28 出处:网络
I\'m aware that to preserve memory usage, UITa开发者_运维百科bleViewCells are reused when scrolling.I have some custom UITableViewCells that have UITextFields in them.After text is inputted to the UIT

I'm aware that to preserve memory usage, UITa开发者_运维百科bleViewCells 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?


sample.h

@interface sample : UIViewController <UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
{

}

@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];
}
0

精彩评论

暂无评论...
验证码 换一张
取 消