如何解决轻按时,UITextField占位符将继续显示
| 我有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];
}
解决方法
实话实说,“ 2”有点令人困惑。但是这里存在一些问题,其中之一是单元重用。
由于单元格已被重用,因此您不应依赖保留其值的文本,而应存储
textFieldDidEndEditing:
方法中键入的内容。为输入或未输入的值维护一个数组(使用[NSNull null]
单例)。在“ 5”方法中,如果看到现有的文本值,则将文本字段的文本设置为该值。这样,您可以抵消单元重用的影响。
另一个问题是插座StreetName
。创建单元格时,我猜测ѭ6将指向正确的文本字段,但是当单元格被重用时会发生什么。 StreetName
将指向最后创建的单元格的文本字段,因此,您在ѭ5do中所做的所有分配对于重复使用的单元格都是不正确的。如果创建一个自定义子类UITableViewCell
,您将在其中执行cell.myTextField.text = [textFieldStrings objectAtIndex:indexPath.row];
,这会容易得多。
作为旁注,
StreetName.delegate = self;
StreetName.tag = indexPath.row;
tableViewCellFields[indexPath.row] = StreetName;
[StreetName setInputAccessoryView:keybdToolbar];
第一行和最后一行是在创建单元格时只需执行一次的操作。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。