【问题标题】:UITextField placeholder keeps showing when tappedUITextField 占位符在点击时一直显示
【发布时间】:2011-09-13 04:46:57
【问题描述】:

我有一个 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];
}

【问题讨论】:

  • 一些格式会很好。代码也会有所帮助。

标签: ios uitextfield placeholder


【解决方案1】:

说实话,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];

第一行和最后一行是您在创建单元格时只需要执行一次的操作。

【讨论】:

  • 关于 cellForRowAtIndexPath 设置输入文本的部分不起作用。我更新了帖子中的代码。
  • 我根据你的代码创建了一个sample project
  • 哦,我明白你的意思了。谢谢!
猜你喜欢
  • 2012-01-21
  • 1970-01-01
  • 1970-01-01
  • 2014-03-28
  • 2012-08-19
  • 1970-01-01
  • 2015-12-02
  • 2013-04-08
  • 1970-01-01
相关资源
最近更新 更多