2010-07-09 34 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

相關問題