2010-07-09 46 views
0

我知道,为了保留内存使用,滚动时会重新使用UITableViewCells。我有一些自定义UITableViewCells其中有UITextFields。文本输入到UITextField后,我滚动,由于细胞重用,该文本丢失。iPhone SDK:在自定义UITableViewCell中创建UITextField文本通过滚动持久化?

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

我该怎么做呢?有人会发布代码示例吗?

回答

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

您应该检查 如果(细胞==零) 分配 和文本框的文本前,应外设置条件。 要获得正确的文本框的引用,您可以使用[单元格子视图]并使用其唯一的“标记”(分配时设置文本字段的标记)来查找文本字段,也可以继承UITableViewCell并将UITextField添加到其数据成员中。 – Sanniv 2010-07-09 07:33:43

+0

非常感谢您的帮助。我将执行此操作,并让你知道它是如何发生的。 – 2010-07-10 16:15:52

相关问题