2010-12-07 4 views
12

У меня есть UITableViewCell (с соответствующим подклассом UITableViewCell, .m & .h), созданным в IB, который содержит UITextField. Этот UITextField подключается к IBOutlet в подклассе UITableViewCell, а также имеет свойство. На моем взгляде таблицы контроллера Я использую эту пользовательскую ячейку с помощью следующего кода:Доступ к UITextField в пользовательском 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?

ответ

21

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

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

Во-первых, на ваш вопрос повторно: доступ к ценности 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; 
     }   
     ... 
} 
+0

Cheers Rog, я попробую это, когда вернусь к своему mac. Интересно, как Apple это делает, как приложение «Настройки», я бы подумал, что буду немного более прямолинейным/более чистым, чем это. Я полагаю, что они, вероятно, делают это совершенно по-другому, и все с кодом тоже. – Darthtong 2010-12-07 12:18:41

8

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

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

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

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

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

- (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; 
} 
2

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

1.Create обычай UITableViewCell класс для ячейки (egtextfieldcell)

2.Now, в textfieldcell.h файла вызова textFieldDelegate

3.In в textfieldcell.м-файл записи методы 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.c reate метода пользовательского делегата в MaintableViewController

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

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

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

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

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

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

0

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

В раскадровки сопротивления на 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

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

Смежные вопросы