如果一个文本字段已经添加到单元格,怎么不创build一个新的文本字段
我正在使用下面的代码在UITableView单元格中创build文本字段:
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;
我创build3个textFields完全相同的方式。 唯一的区别是placeHolder文本。
当popup键盘时,视图向上滚动,textField 1离开屏幕。 返回后,我认为textField正在重新创build。
以下是一些屏幕截图:
细胞第一次出现(看起来很棒):
滚动屏幕后返回(注意第一个文本框):
在单元格1中,当我开始input时,第二个创build的textField的placeHolder消失了,但是第一个textField的占位符保持不变:
两个问题:
- 如何避免在单元格中重新创buildtextField? 或者消除这个问题?
- 当重新创build时,为什么单元格textField上出现单元格3的textField与“活动3:types名称”placeHolder?
我假设这个代码是在cellForRow
tableview的dataSource协议方法。 问题是这种方法被称为多次(有时当你不期望),导致一个新的文本字段被创build并添加到同一单元格。 为了解决此问题,只需在创build单元格时添加文本字段 ,然后在每次调用方法时configuration单元格。 我会build议创build一个表格单元格的子类,但是你可以改变你的代码来达到这个目的:
#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 :) */ ...
我也推荐你看看免费的Sensible TableView框架。 该框架不仅会自动为您创buildinput单元格,还会自动将更改应用回您的对象。 强烈build议,节省了我吨的时间。