UITextField占位符文本覆盖问题

我有一个表视图与三个表格视图单元格。 在单元configuration期间,我将UITextField添加到每个单元格,并且还在所有文本字段上设置了占位符值。 当表视图加载最终的结果如下所示:

加载后的表格视图

我遇到的问题是,当我将任何单元格从屏幕上滚动出来时,他们再次出现占位符文本变得越来越黑暗,如下所示:

较深的占位符文本

当我尝试通过在中input名称或编程方式更改最后一个单元格中的占位符值来更改UITextFieldstring值时,这些属性的旧值将保留,并且新值将覆盖在单元格中,如下所示:

在这里输入图像说明

以下是负责configuration这些单元的方法:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; // Configure the cell... [self configureCell:cell forIndexPath:indexPath]; return cell; } - (void)configureCell:(UITableViewCell *)cell forIndexPath:(NSIndexPath *)indexPath { for (UIView *subview in cell.contentView.subviews) { [subview removeFromSuperview]; } cell.backgroundColor = [UIColor whiteColor]; cell.autoresizesSubviews = YES; cell.clearsContextBeforeDrawing = YES; CGRect textFieldFrame = cell.bounds; textFieldFrame.origin.x += 10; textFieldFrame.size.width -= 10; UITextField *textField = [[UITextField alloc] initWithFrame:textFieldFrame]; textField.adjustsFontSizeToFitWidth = YES; textField.textColor = [UIColor lightGrayColor]; textField.enabled = YES; textField.userInteractionEnabled = NO; textField.autoresizingMask = UIViewAutoresizingFlexibleWidth; textField.clearsContextBeforeDrawing = YES; textField.clearsOnBeginEditing = YES; if (indexPath.section == ATTAddNewTimerSectionName) { textField.placeholder = @"Name"; textField.userInteractionEnabled = YES; textField.delegate = self; textField.returnKeyType = UIReturnKeyDone; textField.clearButtonMode = UITextFieldViewModeWhileEditing; } else if (indexPath.section == ATTAddNewTimerSectionDate) { textField.placeholder = @"Date/Time"; cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; } else if (indexPath.section == ATTAddNewTimerSectionCalendar) { if (self.userCalendarEvent == nil) { textField.placeholder = @"See list of calendar events"; } else { textField.placeholder = nil; textField.placeholder = self.userCalendarEvent.title; } cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; } [cell addSubview:textField]; } 

正如你所看到的,我已经尝试了各种各样的东西,比如在添加一个新的视图到单元格或设置单元格和UITextView上的[UIView setClearsContextBeforeDrawing:YES]之前删除所有的子视图,甚至设置占位符的值为零。

任何指针将不胜感激!

你正在做出这么多人所做的经典错误。 当一个表被滚动时,单元格被重用。

正如所写的,每次使用单元格时,代码都会不断创build并添加新的文本字段。 所以你看到了单元格中有多个文本字段的结果。

您只想将一个文本字段添加到单元格中。 更新您的代码,以便只添加文本字段,如果它不存在。

看来你在代码中有一个逻辑问题。 您将文本字段直接添加到单元格,但您尝试从单元格的contentView删除它。

改变这个:

 [cell addSubview:textField]; 

至:

 [cell.contentView addSubview:textField];