2010-12-07 6 views
12

J'ai un UITableViewCell (avec sous-classe UITableViewCell associée, .m & .h) créé dans IB qui contient un UITextField. UITextField est connecté à un IBOutlet dans la sous-classe UITableViewCell et possède également une propriété. Dans mon contrôleur de vue de la table J'utilise cette cellule personnalisée avec le code suivant:Accès à UITextField dans un UITableViewCell personnalisé

// 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; 

} 

Le UITextField affiche bien et le clavier apparaît quand on clique dessus comme prévu, mais comment puis-je accéder (obtenir la propriété .text) le UITextField que chaque rangée contient? et comment gérer la méthode 'textFieldShouldReturn' des UITextFields?

Répondre

21

Je pense que l'OP essaie de comprendre comment accéder à la valeur UITextField une fois que l'utilisateur a saisi des données dans chaque champ. Cela ne sera pas disponible au moment où les cellules sont créées comme suggéré par @willcodejavaforfood.

J'ai implémenté un formulaire et essayé de le rendre aussi convivial que possible. C'est faisable mais sachez que cela peut devenir compliqué en fonction du nombre de UITableViewCells/UITextFields que vous avez.

Tout d'abord à votre re question: l'accès aux valeurs de UITextField:

1) Faites votre contrôleur de vue une <UITextFieldDelegate>

2) Mettre en œuvre la méthode suivante:

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

J'utilise aussi un syntaxe similaire pour s'assurer que le champ édité en cours est visible:

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

Et enfin, vous pouvez gérer textViewShouldReturn: de manière similaire:

- (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

Bravo Rog, je vais essayer ça quand je reviendrai à mon mac. Je me demande comment Apple le fait, comme l'application Paramètres, j'aurais pensé que je serais un peu plus simple/propre que cela. Je suppose qu'ils le font probablement d'une manière complètement différente et tous avec du code aussi. – Darthtong

8

En cellForRowAtIndexPath: inclure ce code,

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

ensuite accéder à l'textField en utilisant

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

Si vous avez créé une classe pour votre cellule personnalisée je vous conseille de travailler contre elle.

- (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

Il est de manière encore plus simple à résoudre les deux problèmes,

1.Créez une classe UITableViewCell sur mesure pour la cellule, (egtextfieldcell)

2.Now, dans le fichier textfieldcell.h appel textFieldDelegate

3.In le textfieldcell.m méthodes de textFieldDelegate d'écriture de fichiers -à-dire

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

-(void)textFieldDidEndEditing:(UITextField *)textField; 
  1. (premier problème) Maintenant, dans
-(BOOL)textFieldShouldReturn:(UITextField *)textField    
{   
     [self.mytextBox resignFirstResponder];   
     return YES;   
} 

5. (deuxième problème),

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

6.c réer une méthode de délégué personnalisé dans le fichier MaintableViewController.m MaintableViewController

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

7.In écrire la mise en œuvre de la méthode déléguée,

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

8.call la méthode déléguée dans la classe cellulaire et passer la variable dans la didendmethod

9.now, attribuer à l'auto cell.delegate, lors de l'initialisation de la cellule dans uitableview

10.thats Si vous avez la variable passée de textfield à la vue principale, maintenant faire ce que vous voulez avec la variable

0

This tutoriel m'a été utile. Vous pouvez référencer tout objet dont vous avez besoin grâce à l'étiquette.

Dans la traînée Storyboard sur un UIImageView ou UITextField etc., et mettre l'étiquette à 100 (tout ce que vous voulez) puis dans votre - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath utiliser la balise pour le référencer.

Voici quelque chose que vous pourriez faire, rappelez-vous de définir les balises dans le story-board:

- (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

Voici comment j'ai réussi à obtenir le texte à l'intérieur du UITextField dans mon habitude UITableViewCell à Swift. J'ai accédé à ceci à l'intérieur de mon UIButton à l'intérieur d'une autre coutume UITableViewCell qui a un @IBAction sur mon UITableViewController. J'ai seulement une section dans mon UITableViewController mais peu importe de toute façon parce que vous pouvez facilement définir et affecter vous-même.

@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)") 
} 

Chaque fois que je tapais UIButton, il me donne la valeur actualisée du texte dans mon UITextField.