【问题标题】:How NOT to create a new textfield if one textfield has been added to the cell如果已将一个文本字段添加到单元格,如何不创建新文本字段
【发布时间】:2013-07-09 23:51:11
【问题描述】:

我正在使用以下代码在 UITableView 单元格中创建文本字段:

static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil)
{
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
    cell.showsReorderControl = YES;
}

if (indexPath.row == 1)
{
    UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(15,10,260,40)];
    textField.placeholder = @"Activity 1:  Type Name";
    textField.delegate = self;
    textField.clearButtonMode = YES;
    [textField setReturnKeyType:UIReturnKeyDone];
    [cell addSubview:textField];
}

return cell;

我正在以完全相同的方式创建 3 个文本字段。唯一的区别是 placeHolder 文本。

当键盘弹出时,视图向上滚动并且 textField 1 离开屏幕。返回后,我认为正在重新创建 textField。

以下是一些屏幕截图:

单元格第一次出现(看起来很棒):

滚动离开屏幕后返回(注意第一个文本字段):

在第一个单元格中,当我开始输入时,第二个创建的 textField 的 placeHolder 消失了,但第一个 textField 的占位符仍然存在:

两个问题:

  1. 如何避免在单元格中重新创建 textField?或消除这个问题?
  2. 重新创建后,为什么单元格 3 中的 textField 出现在单元格 1 的 textField 中,其 placeHolder 为“活动 3:类型名称”?

【问题讨论】:

  • 不是3,是3和1重叠。这有什么建议吗?

标签: ios objective-c uitableview uitextfield


【解决方案1】:

我假设这段代码在cellForRow tableview dataSource 协议方法中。问题是这个方法被多次调用(有时你不会想到),导致一个新的文本字段被创建并添加到同一个单元格中。为了解决这个问题您只需要在创建单元格时添加一个文本字段,然后在每次调用该方法时配置单元格。我建议创建一个表格单元子类,但您可以将代码更改为此以用于学习目的:

#define kTextFieldTag 1

UITextField* textField = [cell viewWithTag:kTextFieldTag];
if (cell == nil)
{
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
    cell.showsReorderControl = YES;

    /* only called when cell is created */
    textField = [[UITextField alloc] initWithFrame:CGRectMake(15,10,260,40)];
    textField.delegate = self;
    textField.clearButtonMode = YES;
    textField.tag = kTextFieldTag; /* I would recommend a cell subclass with a textfield member over the tag method in real code*/
    [textField setReturnKeyType:UIReturnKeyDone];
    [cell addSubview:textField];
}

/* called whenever cell content needs to be updated */
if (indexPath.row == 1)
{
   textField.placeholder = @"Activity 1:  Type Name";
}
...
/* or replace if checks with with: */
textField.placeholder = [NSString stringWithFormat:@"Activity %i: Type Name", (int)indexPath.row]; /* Handles all fields :) */
...

【讨论】:

    【解决方案2】:

    我还建议您查看免费的Sensible TableView 框架。该框架不仅会自动为您创建输入单元格,还会自动将更改应用回您的对象。强烈推荐,为我节省了大量时间。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-23
      • 1970-01-01
      • 1970-01-01
      • 2019-02-27
      • 2020-06-02
      相关资源
      最近更新 更多