iPhone SDK:通过滚动使自定义UITableViewCell中的UITextField文本持续存在?

时间:2010-07-09 00:06:29

标签: iphone uitableview scroll

我知道为了保留内存使用量,滚动时会重复使用UITableViewCells。我有一些自定义UITableViewCells,其中包含UITextFields。文本输入到UITextField后,我滚动,由于单元格重用,该文本丢失。

如何通过滚动来保持此文本的持续性?我想我可以将每个单元格的文本存储在自己的NSMutableArray索引中。然后,当重用单元格时,我可以用数组数据重新填充它。

我该怎么做呢?有人会非常友好地发布代码示例吗?

1 个答案:

答案 0 :(得分:1)

<强> 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];
}