Подтвердить что ты не робот

Доступ к UITextField в пользовательском UITableViewCell

У меня есть UITableViewCell (с соответствующим UITableViewCell подкласс,.m и .h), созданный в IB, который содержит UITextField. Этот UITextField подключается к IBOutlet в подклассе UITableViewCell, а также имеет свойство. В моем контроллере представления таблицы я использую эту пользовательскую ячейку со следующим кодом:

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"textfieldTableCell"];
    if (cell == nil) {
        // Create a temporary UIViewController to instantiate the custom cell.
        UIViewController *temporaryController = [[UIViewController alloc] initWithNibName:@"TextfieldTableCell" bundle:nil];
        // Grab a pointer to the custom cell.
        cell = (TextfieldTableCell *)temporaryController.view;  
        // Release the temporary UIViewController.
        [temporaryController release];
    }

    return cell;

}

UITextField отображается нормально, и клавиатура появляется при нажатии, как ожидалось, но как мне получить доступ (получить свойство .text) UITextField, который содержит каждая строка? а также как обрабатывать метод textFieldShouldReturn для UITextFields?

4b9b3361

Ответ 1

Я думаю, что OP пытается понять, как получить доступ к значению UITextField после ввода пользователем данных в каждое поле. Это будет недоступно в момент создания ячеек, как было предложено @willcodejavaforfood.

Я использую форму и стараюсь сделать ее максимально удобной для пользователя. Это выполнимо, но имейте в виду, что он может быть запутан в зависимости от количества UITableViewCells/UITextFields, которые у вас есть.

Во-первых, на ваш вопрос re: доступ к значениям UITextField:

1) Сделайте свой контроллер просмотра <UITextFieldDelegate>

2) Внесите следующий метод:

- (void) textFieldDidEndEditing:(UITextField *)textField {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:(CustomCell*)[[textField superview] superview]]; // this should return you your current indexPath

        // From here on you can (switch) your indexPath.section or indexPath.row
        // as appropriate to get the textValue and assign it to a variable, for instance:
    if (indexPath.section == kMandatorySection) {
        if (indexPath.row == kEmailField) self.emailFieldValue = textField.text;
        if (indexPath.row == kPasswordField) self.passwordFieldValue = textField.text;
        if (indexPath.row == kPasswordConfirmField) self.passwordConfirmFieldValue = textField.text;
    }
    else if (indexPath.section == kOptionalSection) {
        if (indexPath.row == kFirstNameField) self.firstNameFieldValue = textField.text;
        if (indexPath.row == kLastNameField) self.lastNameFieldValue = textField.text;
        if (indexPath.row == kPostcodeField) self.postcodeFieldValue = textField.text;
    }   
}

Я также использую аналогичный синтаксис, чтобы убедиться, что текущее отредактированное поле видимо:

- (void) textFieldDidBeginEditing:(UITextField *)textField {
    CustomCell *cell = (CustomCell*) [[textField superview] superview];
    [self.tableView scrollToRowAtIndexPath:[self.tableView indexPathForCell:cell] atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
}

И, наконец, вы можете обрабатывать textViewShouldReturn: аналогичным образом:

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:(CustomCell*)[[textField superview] superview]];
    switch (indexPath.section) {
        case kMandatorySection:
        {
            // I am testing to see if this is NOT the last field of my first section
            // If not, find the next UITextField and make it firstResponder if the user
            // presses ENTER on the keyboard
            if (indexPath.row < kPasswordConfirmField) {
                NSIndexPath *sibling = [NSIndexPath indexPathForRow:indexPath.row+1 inSection:indexPath.section];
                CustomCell *cell = (CustomCell*)[self.tableView cellForRowAtIndexPath:sibling];
                [cell.cellTextField becomeFirstResponder];
            } else {
                // In case this is my last section row, when the user presses ENTER, 
                // I move the focus to the first row in next section
                NSIndexPath *sibling = [NSIndexPath indexPathForRow:kFirstNameField inSection:kOptionalSection];
                MemberLoginCell *cell = (MemberLoginCell*)[self.memberTableView cellForRowAtIndexPath:sibling];
                [cell.cellTextField becomeFirstResponder];
            }
            break;
        }           
        ...
}

Ответ 2

В cellForRowAtIndexPath: включите этот код,

yourTextField.tag=indexPath.row+1; //(tag must be a non zero number)

Затем войдите в текстовый экран, используя

UITextField *tf=(UITextField *)[yourView viewWithTag:tag];

Ответ 3

Существует еще более простой способ решить обе проблемы,

1.Создайте собственный класс uitableviewCell для ячейки (например, textfieldcell)

2. Теперь, в текстовом поле cell.h файл вызывается textFieldDelegate

3. В файле textfieldcell.m напишите textFieldDelegate методы  т.е.

-(BOOL)textFieldShouldReturn:(UITextField *)textField;

-(void)textFieldDidEndEditing:(UITextField *)textField;
  • (первая проблема) Теперь, в
 -(BOOL)textFieldShouldReturn:(UITextField *)textField             
 {          
      [self.mytextBox resignFirstResponder];           
      return YES;        
 }

5. (вторая проблема),

-(void)textFieldDidEndEditing:(UITextField *)textField
{
   nameTextField = mytextBox.text;
}

6.Создайте собственный метод делегата в MaintableViewController

@protocol textFieldDelegate <NSObject>
-(void)textName:(NSString *)name;
 @end

7. В файле MaintableViewController.m напишите реализацию метода делегата,

-(void)textName:(NSString *)name{
    Nametext = name;
    NSLog(@"name = %@",name);
}

8.Вставьте метод делегата в класс ячеек и передайте переменную в методе didendmethod

9. Теперь назначьте self на cell.delegate, когда инициализируется ячейка в uitableview

10. Это означает, что вы получили переменную, переданную из текстового поля в основной вид. Теперь сделайте все, что хотите, с переменной

Ответ 4

Если вы создали класс для своей пользовательской ячейки, я бы посоветовал вам работать против него.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MyCustomCell* cell = (MyCustomCell *) [tableView dequeueReusableCellWithIdentifier:@"BDCustomCell"];
    if (cell == nil) {
        // Load the top-level objects from the custom cell XIB.
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"MyCustomCell" owner:self options:nil];
        // Grab a pointer to the first object (presumably the custom cell, as that all the XIB should contain).
        cell = (MyCustomCell *) [topLevelObjects objectAtIndex:0];
    }

    // This is where you can access the properties of your custom class
    cell.myCustomLabel.text = @"customText";
    return cell;
}

Ответ 5

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

В раскадровке перетащите объект UIImageView или UITextField и т.д. и установите для тега значение 100 (все, что вам нужно), а затем в - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath используйте тег, чтобы ссылаться на него.

Здесь вы можете сделать что-то, просто не забудьте установить теги в раскадровке:

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
 {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

// Configure the cell...
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}

 UITextField *tField = (UITextField *)[cell viewWithTag:100];

return cell;
 }

Ответ 6

Вот как мне удалось получить текст внутри UITextField внутри моего пользовательского UITableViewCell в Swift. Я получил доступ к этому внутри моего UIButton внутри другого пользовательского UITableViewCell, у которого @IBAction на моем UITableViewController. У меня есть только один раздел в моем UITableViewController, но это не имеет значения, потому что вы можете легко установить и назначить это самостоятельно.

@IBAction func submitButtonTapped(sender: UIButton) {
    print("Submit button tapped")

    let usernameCell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0)) as! UsernameTableViewCell
    print("Username: \(usernameCell.usernameTextField.text)")
}

Всякий раз, когда я нажимал свой UIButton, он дает мне обновленное значение текста внутри моего UITextField.