在 UITableView 中选择时未清除 UITextViews

UITextViews not cleared when selected in a UITableView

我正在实现一个带有文本视图的 UITableView 作为我的单元格的内容视图。

当用户按下 return 键时,用户输入的数据将保存在设置字典中:

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == _textFieldOne){
        [settingsDictionary setObject: _textFieldOne.text forKey:@"EntryOneText"];
        [settingsDictionary stringValueForKey:@"textFieldOneValue"];
        [self postNotificationSettingsUpdate:settingsDictionary];
        didTestPostNotificationSettings = YES;
}

当用户 return 返回屏幕时,这些保存的值应该显示在文本字段中,我使用下面的代码完成了这一点:

    //Set the value in the text fields from the settings dictionary
    NSString *textFieldOneText = [self.settingsDictionary       stringValueForKey:@"RedZoneCarsPerManHrMin"];

    _textFieldOne.text = textFieldOneValue;

到目前为止,一切似乎都按预期工作:文本输入已保存,并在用户 return 进入屏幕时显示在文本字段中。但是,如果包含文本字段的 TableView 的 是 select(不是文本字段 本身 ),则文本字段显示如下所示的行为:

似乎文本字段显示了新输入的条目以及上次保存的条目。

编辑 我在下面添加了更多我的 cellForRowAtIndexPath 方法:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForSubscribedRedZoneAlertRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"RedZoneAlertCell";

    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
    }

    cell.backgroundColor = [UIColor colorWithRed:0.922 green:0.937 blue:0.949 alpha:1];

    UISwitch *cellSwitch = nil;

    NSNumber *position = enabledRedZoneAlertRows[indexPath.row];


switch (position.integerValue) {
    case CarPerManHourRow: {
        cell.textLabel.text = NSLocalizedString(@"Label", @"Label Row");
        cellSwitch = [[UISwitch alloc] init];
        cellSwitch.on = [[NSUserDefaults standardUserDefaults] boolForKey:SwitchKey];
        cellSwitch.tag = SwitchTag;
        [cellSwitch addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
        cell.accessoryView = cellSwitch;

        if ([[self.settingsDictionary valueForKey:@"RedZoneCarsPerManHrOnOff"]isEqual: @"1"]){
            [cellSwitch setOn:YES];
        }
        break;
    }
    case TextFieldRow: {
        static NSString *CellIdentifier = @"ConfigCell";
        cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
        [cell.contentView addSubview:_textFieldOne];
        [cell.contentView addSubview:_textFieldTwo];
        [cell.contentView addSubview:_spacingLabel];
        }

        cell.backgroundColor = [UIColor colorWithRed:0.922 green:0.937 blue:0.949 alpha:1];

        _textFieldOne = [[UITextField alloc]initWithFrame:CGRectMake(25, 0, 50, 30)];
        _textFieldTwo = [[UITextField alloc]initWithFrame:CGRectMake(100, 0, 50, 30)];

        _textFieldOne.delegate = self;
        _textFieldTwo.delegate = self;

        _textFieldOne.placeholder = @"Auto";
        _textFieldTwo.placeholder = @"Auto";
        [_textFieldOne setTextAlignment:NSTextAlignmentCenter];
        [_textFieldTwo setTextAlignment:NSTextAlignmentCenter];

        //Set the value in the text fields from the settings dictionary
       NSString *textFieldOneText = [self.settingsDictionary stringValueForKey:@"RedZoneCarsPerManHrMin"];
       NSString *textFieldTwoText = [self.settingsDictionary stringValueForKey:@"RedZoneCarsPerManHrMax"];

        NSString *carsPerManHrMax = [self.settingsDictionary stringValueForKey:@"RedZoneCarsPerManHrMax"];
        NSString *carsPerManHrMax = [self.settingsDictionary stringValueForKey:@"RedZoneCarsPerManHrMax"];

        _textFieldOne.text = textFieldOneValue;
        _textFieldTwo.text = textFieldTwoValue

        _textFieldOne.backgroundColor = [UIColor whiteColor];
        _textFieldTwo.backgroundColor = [UIColor whiteColor];
        _textFieldOne.tintColor = [UIColor blackColor];
        _textFieldTwo.tintColor = [UIColor blackColor];

        [_textFieldOne.layer setCornerRadius:7.0f];
        [_textFieldTwo.layer setCornerRadius:7.0f];

        [_textFieldOne setKeyboardType:UIKeyboardTypeNumbersAndPunctuation];
        [_textFieldTwo setKeyboardType:UIKeyboardTypeNumbersAndPunctuation];

        _textFieldOne.returnKeyType = UIReturnKeyNext;
        _textFieldTwo.returnKeyType = UIReturnKeyDone;

        _spacingLabel = [[UILabel alloc] initWithFrame:CGRectMake(70, 0, 35, 30)];
        _spacingLabel.text = @"–";
        _spacingLabel.textColor = [UIColor colorWithRed:0.658 green:0.658 blue:0.658 alpha:1];
        [_spacingLabel setTextAlignment:NSTextAlignmentCenter];
        _spacingLabel.backgroundColor = [UIColor clearColor];

        //[cell.contentView addSubview:_textFieldOne];
        //[cell.contentView addSubview:_textFieldTwo];
        //[cell.contentView addSubview:_spacingLabel];

        break;
    }
   return cell;
}

编辑两个 以下是我尝试根据 jherran 的回答解决我的问题。但是,我仍然遇到同样的问题。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForSubscribedRedZoneAlertRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"RedZoneAlertCell";

    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
    }

    cell.backgroundColor = [UIColor colorWithRed:0.922 green:0.937 blue:0.949 alpha:1];

    UISwitch *cellSwitch = nil;

    NSNumber *position = enabledRedZoneAlertRows[indexPath.row];

    switch (position.integerValue) {
        case CarPerManHourRow: {
            cell.textLabel.text = NSLocalizedString(@"Label", @"Label Row");
            cellSwitch = [[UISwitch alloc] init];
            cellSwitch.on = [[NSUserDefaults standardUserDefaults] boolForKey:SWSettingCarsPerManHour];
            cellSwitch.tag = SaveCarsPerManHourTag;
            [cellSwitch addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
            cell.accessoryView = cellSwitch;

            if ([[self.settingsDictionary valueForKey:@"RedZoneCarsPerManHrOnOff"]isEqual: @"1"]){
                [cellSwitch setOn:YES];
            }
            break;
        }
        case CarsPerManHourConfigRow: {

            static NSString *CellIdentifier = @"ConfigCell";
            cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];

                cell.backgroundColor = [UIColor colorWithRed:0.922 green:0.937 blue:0.949 alpha:1];

                _carsPerManHourMinTextField = [[UITextField alloc]initWithFrame:CGRectMake(25, 0, 50, 30)];
                _carsPerManHourMaxTextField = [[UITextField alloc]initWithFrame:CGRectMake(100, 0, 50, 30)];

                _textFieldOne.delegate = self;
                _textFieldTwo.delegate = self;

                _textFieldOne.placeholder = @"Auto";
                _textFieldTwo.placeholder = @"Auto";
                [_textFieldOne setTextAlignment:NSTextAlignmentCenter];
                [_textFieldTwo setTextAlignment:NSTextAlignmentCenter];




                _textFieldOne.backgroundColor = [UIColor whiteColor];
                _textFieldTwo.backgroundColor = [UIColor whiteColor];
                _textFieldOne.tintColor = [UIColor blackColor];
                _textFieldTwo.tintColor = [UIColor blackColor];


                [_textFieldOne.layer setCornerRadius:7.0f];
                [_textFieldTwo.layer setCornerRadius:7.0f];

                [_textFieldOne setKeyboardType:UIKeyboardTypeNumbersAndPunctuation];
                [_carsPerManHourMaxTextField setKeyboardType:UIKeyboardTypeNumbersAndPunctuation];

                _textFieldOne.returnKeyType = UIReturnKeyNext;
                _textFieldTwo.returnKeyType = UIReturnKeyDone;

                _spacingLabel = [[UILabel alloc] initWithFrame:CGRectMake(70, 0, 35, 30)];
                _spacingLabel.text = @"–";
                _spacingLabel.textColor = [UIColor colorWithRed:0.658 green:0.658 blue:0.658 alpha:1];
                [_spacingLabel setTextAlignment:NSTextAlignmentCenter];
                _spacingLabel.backgroundColor = [UIColor clearColor];

                NSLog(@"%@", _textFieldOne.text);
                NSLog(@"%@",_carsPerManHourMaxTextField.text);

                [cell.contentView addSubview: _textFieldOne];
                [cell.contentView addSubview: _textFieldTwo];
                [cell.contentView addSubview:_spacingLabel];

                cell.tag = 1;
            }

            else {
                _textFieldOne = (UITextField *)[cell.contentView viewWithTag:1];
                _textFieldTwo = (UITextField *)[cell.contentView viewWithTag:1];
                _spacingLabel = (UILabel *)[cell.contentView viewWithTag:1];
            }

            NSString * _textFieldOne = [self.settingsDictionary stringValueForKey:@"RedZoneCarsPerManHrMin"];
            NSString *carsPerManHrMax = [self.settingsDictionary stringValueForKey:@"RedZoneCarsPerManHrMax"];

            _textFieldOne.text = carsPerManHrMin;
            _textFieldTwo.text = carsPerManHrMax;

如何修改我的代码以防止这种行为发生?

检查您的 cellForRowAtIndexPath,因为单元格被重复使用,您可能没有加载单元格 属性。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    /*
     *   This is an important bit, it asks the table view if it has any available cells
     *   already created which it is not using (if they are offscreen), so that it can
     *   reuse them (saving the time of alloc/init/load from xib a new cell ).
     *   The identifier is there to differentiate between different types of cells
     *   (you can display different types of cells in the same table view)
     */

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifier"];

    /*
     *   If the cell is nil it means no cell was available for reuse and that we should
     *   create a new one.
     */
    UILabel *label;
    if (cell == nil) {

        /* 
         *   Actually create a new cell (with an identifier so that it can be dequeued). 
         */

        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MyIdentifier"] autorelease];

        label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
        cell.tag = 1;
        [cell.contentView addSubview:label];

    } else {

        label = (UILabel *)[cell.contentView viewWithTag:1];

    }

    /*
     *   Now that we have a cell we can configure it to display the data corresponding to
     *   this row/section
     */

     label.text = @"whatever";
}

编辑:当您的单元格退出并被重复使用时,每次重复使用该单元格时您都会添加一个视图 ([cell.contentView addSubview:_textFieldOne])。

好的,果然如我所料。每次从重用队列中取出单元格时,您都会创建一个新的文本字段实例并将其添加到内容视图中。所以基本上内容视图正在堆积新的文本字段。 你应该做的是

1) 拥有一个自定义单元格并使该单元格成为唯一 class 负责其内部结构的单元格

2) 仅公开一个配置方法以将原始文本传递给单元格

3) 当重新使用 thr cell 时调用该配置方法。

4) 在自定义单元格内保留对文本字段的引用,以便能够随时更新文本值,包括。当它在 cellforrowatindexpath

中被回收时