Accessing UITextField in a custom UITableViewCell

后端 未结 6 1602
无人及你
无人及你 2020-12-03 08:38

I have a UITableViewCell (with associated UITableViewCell sub class, .m & .h) created in IB which contains a UITextField. This UITextField is connected up to an IBOutlet

相关标签:
6条回答
  • 2020-12-03 08:42

    This is how I managed to get the text inside the UITextField inside my custom UITableViewCell in Swift. I accessed this inside my UIButton inside another custom UITableViewCell that has an @IBAction on my UITableViewController. I only have one section in my UITableViewController but that doesn't matter anyway because you can easily set and assign this yourself.

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

    Whenever I tapped my UIButton, it gives me the updated value of the text inside my UITextField.

    0 讨论(0)
  • 2020-12-03 08:44

    This tutorial was helpful to me. You can reference whatever object you need through the tag.

    In the Storyboard drag on a UIImageView or UITextField etc. and set the tag to 100 (whatever you want) then in your - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath use the tag to reference it.

    Here's something you could do, just remember to set the tags in the storyboard:

     - (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 讨论(0)
  • 2020-12-03 08:45

    I think what the OP is trying to understand is how to access the UITextField value once the user has entered data into each fields. This will not be available at the time the cells are created as suggested by @willcodejavaforfood.

    I've been implementing a form and trying to make it as user friendly as possible. It is doable but be aware that it can get quite convoluted depending on the number of UITableViewCells / UITextFields you have.

    Firstly to your question re: accessing the values of UITextField:

    1) Make your view controller a <UITextFieldDelegate>

    2) Implement the following method:

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

    I also use a similar syntax to make sure the current edited field is visible:

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

    And finally, you can handle textViewShouldReturn: in a similar way:

    - (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 讨论(0)
  • 2020-12-03 08:45

    In cellForRowAtIndexPath: include this code,

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

    Then access the textField using

    UITextField *tf=(UITextField *)[yourView viewWithTag:tag];
    
    0 讨论(0)
  • 2020-12-03 08:46

    There is even more simpler way to solve both problems,

    1.Create a custom uitableviewCell class for the cell, (e.g.textfieldcell)

    2.Now, in the textfieldcell.h file call textFieldDelegate

    3.In the textfieldcell.m file write textFieldDelegate methods ie

    -(BOOL)textFieldShouldReturn:(UITextField *)textField;
    
    -(void)textFieldDidEndEditing:(UITextField *)textField;
    
    1. (first problem)Now, in
     -(BOOL)textFieldShouldReturn:(UITextField *)textField             
     {          
          [self.mytextBox resignFirstResponder];           
          return YES;        
     }
    

    5.(second problem),

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

    6.create a custom delegate method in the MaintableViewController

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

    7.In MaintableViewController.m file write the implementation of the delegate method,

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

    8.call the delegate method in the cell class , and pass the variable in the didendmethod

    9.now, assign self to cell.delegate ,when initializing the cell in uitableview

    10.thats it you got the variable passed from textfield to the main view, Now do whatever u want with the variable

    0 讨论(0)
  • 2020-12-03 09:07

    If you have created a class for your custom cell I'd advise you to work against it.

    - (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;
    }
    
    0 讨论(0)
提交回复
热议问题