【问题标题】:iPhone SDK: Making UITextField text in a custom UITableViewCell persist through scrolls?iPhone SDK:使自定义 UITableViewCell 中的 UITextField 文本通过滚动持续存在?
【发布时间】:2010-07-09 00:06:29
【问题描述】:

我知道为了节省内存使用,UITableViewCells 在滚动时会被重用。我有一些自定义的UITableViewCells,其中包含UITextFields。将文本输入到UITextField 并滚动后,由于单元格重用,该文本丢失了。

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

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

【问题讨论】:

    标签: iphone uitableview scroll


    【解决方案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];
    }
    

    【讨论】:

    • 您应该在分配之前检查是否 (cell==nil) 并且文本字段的文本应该设置在条件之外。要获得正确的文本字段引用,您可以使用 [cell subviews] 并找到具有唯一“标签”的文本字段(在分配时设置文本字段的标签),或者您可以继承 UITableViewCell 并在其数据成员中添加 UITextField。
    • 非常感谢您的帮助。我会实现它,并让你知道它是如何进行的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-28
    • 2011-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多