【问题标题】:Add a UITextField that retains its text in a UITableViewCell添加一个在 UITableViewCell 中保留其文本的 UITextField
【发布时间】:2014-07-02 16:40:10
【问题描述】:

如何实现一个带有 textField 的 UITableViewCell?我在 StackOverflow 上遇到过一些类似的问题,但我发现其中大多数都处理 tableView 的显示始终不变并且确切知道值在哪里的情况。对于我的实现,部分的数量和每部分的行数由用户确定,可以是任何东西。我已经能够在单元格中获得一个 textField,但是当我滚动表格并且单元格从视图中消失时,我发现输入的任何文本都丢失了。这就是我目前所拥有的

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [self.myTableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];

    UITextField *myTextField = [[UITextField alloc]
                          initWithFrame:CGRectMake(215, (cell.contentView.bounds.size.height-30)/2, 60, 30)];

    [myTextField setDelegate: self];
    myTextField.tag = indexPath.section;
    NSLog(@"%ld", (long)myTextField.tag);


    myTextField.placeholder = @"0%";
    myTextField.borderStyle = UITextBorderStyleRoundedRect;

    [cell addSubview:myTextField];

    cell.textLabel.text = self.cellLabels[indexPath.section];
    return cell;
}

我知道问题出在哪里,我只是想不出解决办法。即使我以某种方式将用户在每个 textField 中输入的所有内容存储在一个数组中,当每个字段从屏幕外返回时,我也无法设置每个字段的文本,因为 cellForRowAtIndexPath 再次被调用并且 textField 被重绘。

这正是我想要的,功能方面。但是“Paper1”和“Paper2”可能是不同的部分...

【问题讨论】:

    标签: ios objective-c uitableview uitextfield


    【解决方案1】:

    使用视图模型。将每个单元格的文本存储在一个数组中,然后在 cellForRowAtIndexpath 中设置文本。

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        UITableViewCell *cell = [self.myTableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    
        UITextField *myTextField = [[UITextField alloc]
                          initWithFrame:CGRectMake(215, (cell.contentView.bounds.size.height-30)/2, 60, 30)];
    
        [myTextField setDelegate: self];
        myTextField.tag = indexPath.section;
        NSLog(@"%ld", (long)myTextField.tag);
    
       myTextField.placeholder = @"0%";
       myTextField.borderStyle = UITextBorderStyleRoundedRect;
        myTextField.text = [self textForCellAtIndexPath:indexPath];
        [cell addSubview:myTextField];
    
        cell.textLabel.text = self.cellLabels[indexPath.section];
        return cell;
    

    }

    【讨论】:

    • 部分问题是文本是由用户决定的,我无法预测他们的输入并存储在数组中。
    • 我并不是建议你预测他们的输入。您需要存储他们输入的文本。由于某种原因您尚未共享,您已设置委托。现在您只需要在输入时将文本记录在视图模型中。
    • 基本上,不要将文本字段用作您的主要文本存储。使用视图模型(字符串数组或“论文”?)。
    • 知道了,试试这个
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-21
    • 1970-01-01
    • 2023-03-12
    相关资源
    最近更新 更多