UITextField в ячейке UITableView возвращается как (null) - PullRequest
0 голосов
/ 01 января 2011

Два текстовых поля находятся в UItableView.Сборка завершается без ошибок.Когда я ввожу данные для входа и нажимаю кнопку отправки в UINavController, первое поле возвращается как (ноль).Я не могу найти причину, по которой это происходит.

Вот код, который я использую:

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

    static NSString *CellIdentifier = @"Cell";

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

    // Configure the cell.

    if ([indexPath section] == 0) {
        tUser = [[UITextField alloc] initWithFrame:CGRectMake(110, 10, 185, 30)];
        tUser.adjustsFontSizeToFitWidth = YES;
        tUser.textColor = [UIColor blackColor];

        tPass = [[UITextField alloc] initWithFrame:CGRectMake(110, 10, 185, 30)];
        tPass.adjustsFontSizeToFitWidth = YES;
        tPass.textColor = [UIColor blackColor];

            if ([indexPath row] == 0) {
                tUser.placeholder = @"user@domain.com";
                tUser.keyboardType = UIKeyboardTypeEmailAddress;
                tUser.returnKeyType = UIReturnKeyNext;
            }
            if ([indexPath row] == 1) {
                tPass.placeholder = @"Required";
                tPass.keyboardType = UIKeyboardTypeDefault;
                tPass.returnKeyType = UIReturnKeyDone;
                [tPass addTarget:self
                                      action:@selector(save:)
                forControlEvents:UIControlEventEditingDidEndOnExit];

                tPass.secureTextEntry = YES;
            }
        }

        tUser.autocorrectionType = UITextAutocorrectionTypeNo;
        tUser.autocapitalizationType = UITextAutocapitalizationTypeNone;
        tUser.textAlignment = UITextAlignmentLeft;

        tPass.autocorrectionType = UITextAutocorrectionTypeNo;
        tPass.autocapitalizationType = UITextAutocapitalizationTypeNone;
        tPass.textAlignment = UITextAlignmentLeft;

        tUser.clearButtonMode = UITextFieldViewModeNever;
        tPass.clearButtonMode = UITextFieldViewModeNever;

        [tUser setEnabled:YES];
        [tPass setEnabled:YES];

        //[tUser release];
        //[tPass release];

     // Email & Password Section
        if ([indexPath row] == 0) { // Email
            cell.textLabel.text = @"Username";
            [cell addSubview:tUser];
        }
        else {
            cell.textLabel.text = @"Password";
            [cell addSubview:tPass];
        }

    return cell;    
}

-(IBAction) save: (id) sender {

        if ([tPass text] == nil) {
            UIAlertView *alertV = [[UIAlertView alloc] initWithTitle:@"Error" 
                                                            message:@"There was no password entered, please enter the correct password and try again." 
                                                           delegate:self 
                                                  cancelButtonTitle:@"Okay" 
                                                  otherButtonTitles:nil];
            [alertV show];
            [alertV release];
        }
        else {
            NSLog(@"we can do something here soon...");

            //NSString *tUserString = [[NSString alloc] initWithFormat:@"Hello: %@", tUser.text];

            NSLog(@"We saved their username: %@", [tUser text]);
            NSLog(@"We saved their password: %@", [tPass text]);


        }

    }

1 Ответ

0 голосов
/ 01 января 2011

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

Когда вы удаляете ячейку из очереди, эта ячейка будет иметь свои подпредставления без изменений, поэтомуВы должны использовать свойство tag, чтобы извлечь текстовое поле, которое уже существует, и обновлять текст на нем, вместо того, чтобы каждый раз создавать новое текстовое поле.

Кроме того, лучшим подходом было бы создание собственного подкласса UITableViewCellэто включает в себя текстовое поле со свойствами, которые позволяют вам легко получить доступ к встроенным текстовым полям.Затем в вашем методе tableView:didSelectRowWithIndexPath: вы можете получить доступ к конкретной ячейке выбранной строки.Чтобы получить ячейку, вы отправляете сообщение cellForRowAtIndexPath: экземпляру tableView.Когда у вас есть ячейка, вы можете получить доступ к пользовательским свойствам для получения имени пользователя и пароля.

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