我有一个 UITableView
足够高,需要滚动。表中最顶部的单元格包含一个 UITextField
,供用户输入一些文本。
构建它的标准方法可能是创建和添加文本字段并将其添加到在 cellFOrRowAtIndexPath:
中创建或回收的单元格中:但是,这种不断的重新创建意味着输入的文本当单元格滚出并返回 View 时,该字段将被删除。
目前我找到的解决方案建议使用 UITextField
委托(delegate)来跟踪文本的变化并将其存储在 iVar 或属性中。我想知道为什么推荐这种方法而不是我正在使用的更简单的方法:
我正在 UITableViewController
的 init 方法中创建 UITextField
并立即将其存储在属性中。在 cellFOrROwAtIndexPath
中,我只是添加了预先存在的字段,而不是初始化一个新字段。单元格本身可以毫无问题地回收,但因为我一直使用唯一的 UITextField
,所以内容得以保留。
这是一个合理的方法吗?可能会出什么问题?任何改进(也许我仍然可以在 cellForRowAtIndexPath
中创建字段,但首先检查该属性是否为 nil?)
最佳答案
当您在 cellForRowAtIndexPath
中创建单元格时,您必须为第一个单元格使用一个可重用标识符(即 cellId1),为其余单元格使用另一个标识符(即 cellId2)。
如果这样做,当您通过调用 [tableView dequeueReusableCellWithIdentifier:@"cellId1"]
获取第一个元素的单元格时,您将始终获得相同的对象,并且不会被其他单元格重用.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
MyCell *cell = nil;
// Only for first row
if (indexPath.row == 0) {
static NSString *cellId1 = @"cellId1";
cell = [tableView dequeueReusableCellWithIdentifier:cellId1];
if (cell == nil) {
cell = [[MyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId1];
}
}
else {
static NSString *cellId2 = @"cellId2";
cell = [tableView cellId2];
if (cell == nil) {
cell = [[MyCell alloc] initWithStyle:UITableViewCellStyleDefault cellId2];
}
}
// do whatever
return cell;
}
关于ios - UITableViewCell 中的 UITextField - 防止文本重置的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18535679/