Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing UITextField in a custom UITableViewCell

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 in the UITableViewCell sub class and also has a property. In my table view controller I am using this custom cell with the following code:

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

}

The UITextField displays fine and the keyboard pops up when clicked as expected, but how do I access (get .text property) the UITextField that each row contains? and also how do I handle the 'textFieldShouldReturn' method of the UITextFields?

like image 644
Darthtong Avatar asked Dec 07 '10 10:12

Darthtong


4 Answers

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.

like image 180
jaytrixz Avatar answered Oct 04 '22 16:10

jaytrixz


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;
        }           
        ...
}
like image 22
Rog Avatar answered Nov 14 '22 21:11

Rog


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];
like image 8
KingofBliss Avatar answered Nov 14 '22 20:11

KingofBliss


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

like image 2
Priyan Haridas Avatar answered Nov 14 '22 20:11

Priyan Haridas