UITextField повторное использование текста в UITextField случайным образом - PullRequest
0 голосов
/ 24 ноября 2011

Это расширение этого вопроса здесь: UITextField случайным образом повторно использует текст в табличном представлении

У меня проблемы с таблицей, в каждой ячейке которой есть поля UITextFields. Я заметил, что текст по-прежнему используется случайным образом в неправильных ячейках, хотя я, кажется, правильно его сохраняю.

 else if (tableView == self.vitalsTableView)
    {
        if ([indexPath row] == 2) {
            CellIdentifier = @"bloodPressureCell";
            BloodPressureTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            cell.textField1.text = [self.vitalsDictionary objectForKey:@"blood_pressure_1"];
            cell.textField2.text = [self.vitalsDictionary objectForKey:@"blood_pressure_2"];
            self.bloodPressureTextField1 = cell.textField1;
            self.bloodPressureTextField2 = cell.textField2;
            return cell;
        }
        else if ([indexPath row] == 9){
            CellIdentifier = @"statusCell";
            SmokingStatusTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            return cell;
        }
        else if ([indexPath row] == 10){
            CellIdentifier = @"vitalsCell";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            return cell;
        }
        else{
            CellIdentifier = @"textCell";
            VitalsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            switch (indexPath.row) {
                case 0:
                    cell.vitalsLabel.text = @"Temperature";
                    cell.textField.text = [self.vitalsDictionary objectForKey:@"temperature"];
                    self.temperatureTextField = cell.textField;
                    break;
                case 1:
                    cell.vitalsLabel.text = @"Pulse";
                    cell.textField.text = [self.vitalsDictionary objectForKey:@"pulse"];
                    self.pulseTextField = cell.textField;
                    break;
                case 3:
                    cell.vitalsLabel.text = @"Respiratory Rate";
                    cell.textField.text = [self.vitalsDictionary objectForKey:@"respiratory_rate"];
                    self.respiratoryRateTextField = cell.textField;
                    break;
                case 4:
                    cell.vitalsLabel.text = @"Oxygen Saturation";
                    cell.textField.text = [self.vitalsDictionary objectForKey:@"oxygen_saturation"];
                    self.oxygenSaturationTextField = cell.textField;;
                    break;
                case 5:
                    cell.vitalsLabel.text = @"Height";
                    cell.textField.text = [self.vitalsDictionary objectForKey:@"height"];
                    self.heightTextField = cell.textField;
                    break;
                case 6:
                    cell.vitalsLabel.text = @"Weight";
                    cell.textField.text = [self.vitalsDictionary objectForKey:@"weight"];
                    self.weightTextField = cell.textField;
                    break;
                case 7:
                    cell.vitalsLabel.text = @"BMI";
                    cell.textField.text = [self.vitalsDictionary objectForKey:@"bmi"];
                    self.bmiTextField = cell.textField;
                    break;
                case 8:
                    cell.vitalsLabel.text = @"Pain (1-10)";
                    cell.textField.text = [self.vitalsDictionary objectForKey:@"pain"];
                    self.painTextField = cell.textField;
                    break;
                default:
                    break;
            }
            return cell;
        }

- (void) textFieldDidEndEditing:(UITextField *)textField{
    if (textField == temperatureTextField){
        [self.vitalsDictionary setObject:self.temperatureTextField.text forKey:@"temperature"];
    }
    else if (textField == pulseTextField){
        [self.vitalsDictionary setObject:self.pulseTextField.text forKey:@"pulse"];
    }
    else if (textField == respiratoryRateTextField){
        [self.vitalsDictionary setObject:self.respiratoryRateTextField.text forKey:@"respiratory_rate"];
    }
    else if (textField == oxygenSaturationTextField){
        [self.vitalsDictionary setObject:self.oxygenSaturationTextField.text forKey:@"oxygen_saturation"];
    }
    else if (textField == heightTextField){
        [self.vitalsDictionary setObject:self.heightTextField.text forKey:@"height"];
    }
    else if (textField == weightTextField){
        [self.vitalsDictionary setObject:self.weightTextField.text forKey:@"weight"];
    }
    else if (textField == bmiTextField){
        [self.vitalsDictionary setObject:self.bmiTextField.text forKey:@"bmi"];
    }
    else if (textField == painTextField){
        [self.vitalsDictionary setObject:self.painTextField.text forKey:@"pain"];
    }
    else if (textField == bloodPressureTextField1){
        [self.vitalsDictionary setObject:self.bloodPressureTextField1.text forKey:@"blood_pressure_1"];
    }
    else if (textField == bloodPressureTextField2){
        [self.vitalsDictionary setObject:self.bloodPressureTextField2.text forKey:@"blood_pressure_2"];
    }
}

Ответы [ 2 ]

0 голосов
/ 24 ноября 2011

В дополнение к правильному ответу @ Barum относительно доступа к текстовым полям у вас также есть проблема с созданием ячеек.Вы удаляете из кэша ячейки, но я не вижу, чтобы ваш код создавал новую ячейку, если снятие очереди возвращает ноль.Вам необходимо сделать следующее:

else if (tableView == self.vitalsTableView) {
    if ([indexPath row] == 2) {
        CellIdentifier = @"bloodPressureCell";
        BloodPressureTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            // create cell if nothing dequeued
            cell = [[BloodPressureTableViewCell alloc] init...]; // use an appropriate initializer
            cell.textField1.tag = MyTextFieldTagBloodPressure1;
            cell.textField2.tag = MyTextFieldTagBloodPressure2; 
        }
        // configure the cell
        cell.textField1.text = [self.vitalsDictionary objectForKey:@"blood_pressure_1"];
        cell.textField2.text = [self.vitalsDictionary objectForKey:@"blood_pressure_2"];
        return cell;
    }
    // do the same for all cell types

Примечание. В приведенном выше примере предполагается, что вы определяете перечисление для значений тегов.Я рекомендую это, поскольку это делает код более читабельным, и вам не нужно будет помнить, какое целое число является каким типом поля.

0 голосов
/ 24 ноября 2011

Вы не можете проверить, выполнив textField == pulseTextField, поскольку UITableview будет повторно использовать ячейки непредсказуемым образом, если совпадают идентификаторы повторного использования.Вы сохраняете ссылку на текстовое поле, но при прокрутке вверх и вниз этой ячейке может быть присвоен другой индекс.Таким образом, вы можете получить дублирующую ссылку на одно и то же текстовое поле, поскольку некоторые ячейки могут быть за кадром с устаревшей дублирующейся ссылкой.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...