Доступ к UITextField в пользовательском UITableViewCell - PullRequest
12 голосов
/ 07 декабря 2010

У меня есть 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?

Ответы [ 6 ]

21 голосов
/ 07 декабря 2010

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

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

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

1) Сделайте ваш контроллер вида a <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;
        }           
        ...
}
8 голосов
/ 07 декабря 2010

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

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

Затем получите доступ к textField, используя

UITextField *tf=(UITextField *)[yourView viewWithTag:tag];
2 голосов
/ 08 августа 2012

Существует еще более простой способ решения обеих проблем:

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

2. Теперь в файле textfieldcell.hвызов textFieldDelegate

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

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

-(void)textFieldDidEndEditing:(UITextField *)textField;
  1. (первая проблема) Теперь, в
 -(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.call метода делегата в классе ячеек, и передать переменную в методе didendmed

9.now, присвоить себя cell.delegate, при инициализации ячейки в uitableview

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

0 голосов
/ 04 декабря 2015

Вот так мне удалось получить текст внутри 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.

0 голосов
/ 03 апреля 2013

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

В раскадровке перетащите на 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;
 }
0 голосов
/ 07 декабря 2010

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

- (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's 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;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...