我有3行的表格视图。每行具有相同的自定义tableviewcell和uitextfield,但占位符属性不同。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = @"NewDestinationCell";
NewDestinationCell *cell = (NewDestinationCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
[cellNib instantiateWithOwner:self options:nil];
cell = editCell;
self.editCell = nil;
cell.detailTextField.delegate = self;
cell.detailTextField.tag = indexPath.row;
[cell.detailTextField setInputAccessoryView:keybdToolbar];
}
if ([[textFieldStrings objectAtIndex:indexPath.row] length] != 0)
cell.detailTextField.text = [textFieldStrings objectAtIndex:indexPath.row];
return cell;
}
当我点击文本字段并输入一些文本时,转到另一个文本字段,然后在输入了我的文本的情况下返回到该文本字段,这会删除我键入的内容,而代之以占位符文本。我是否必须实现commitEditingStyle方法?每个表行中的文本字段都链接到相同的uitextfield出口。也许那是为什么?这是我用来遍历三行的代码。
- (void)textFieldDidBeginEditing:(UITextField *)textField {
[textField becomeFirstResponder];
textField.text = [textFieldStrings objectAtIndex:textField.tag];
currTextField = textField;
if (currTextField.tag == [self.tableView numberOfRowsInSection:0]-1) {
NextButton.enabled = NO;
PrevButton.enabled = YES;
}
if (currTextField.tag == 0) {
PrevButton.enabled = NO;
NextButton.enabled = YES;
}
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
[textFieldStrings replaceObjectAtIndex:textField.tag withObject:textField.text];
[textField resignFirstResponder];
}
- (IBAction)PrevTextField:(id)sender {
[tableViewCellFields[currTextField.tag-1] becomeFirstResponder];
}
- (IBAction)NextTextField:(id)sender {
[tableViewCellFields[currTextField.tag+1] becomeFirstResponder];
}
最佳答案
说实话,IBOutlet
有点令人困惑。但是这里存在一些问题,其中之一是单元重用。
由于单元已被重用,因此您不应该依赖保留其值的文本,而应该在textFieldDidEndEditing:
方法中存储键入的内容。为输入或未输入的值维护一个数组(使用[NSNull null]
singleton)。在cellForRowAtIndexPath:
方法中,如果看到现有的文本值,则将文本字段的文本设置为该值。这样,您可以抵消单元重用的影响。
另一个问题是出口StreetName
。创建单元格时,我猜StreetName
将指向正确的文本字段,但是当单元格被重用时会发生什么。 StreetName
将指向最后创建的单元格的文本字段,结果您在cellForRowAtIndexPath:
中所做的所有分配对于重复使用的单元格都是不正确的。如果您创建UITableViewCell
的自定义子类,然后在其中创建cell.myTextField.text = [textFieldStrings objectAtIndex:indexPath.row];
,这会容易得多。
作为旁注,
StreetName.delegate = self;
StreetName.tag = indexPath.row;
tableViewCellFields[indexPath.row] = StreetName;
[StreetName setInputAccessoryView:keybdToolbar];
第一行和最后一行是在创建单元格时只需执行一次的操作。
关于ios - 点击时,UITextField占位符不断显示,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6318590/