且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如果一个文本字段已添加到单元格中,如何不创建新的文本字段

更新时间:2023-01-13 15:59:51

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

I am assuming this code is in the cellForRow tableview dataSource protocol method. The problem is that this method is called multiple times (sometimes when you wouldn't expect), causing a new text field to be created and added to the same cell. In order to resolve this issue you need to add a text field only when the cell is created, and then configure the cells each time the method is called. I would recommend creating a table cell subclass, but you can change your code to this for learning purposes:

#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 :) */
...