我知道为了保留内存使用量,滚动时会重复使用UITableViewCells
。我有一些自定义UITableViewCells
,其中包含UITextFields
。文本输入到UITextField
后,我滚动,由于单元格重用,该文本丢失。
如何通过滚动来保持此文本的持续性?我想我可以将每个单元格的文本存储在自己的NSMutableArray
索引中。然后,当重用单元格时,我可以用数组数据重新填充它。
我该怎么做呢?有人会非常友好地发布代码示例吗?
答案 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];
}