JMD
JMD

Reputation: 1590

moving to next UITextField in different cells in grouped TableView

I have a ViewController with a grouped tableview added. Some cells contain textfields. I would like to switch the first responder to the next textfield in the list of cells when a user presses the return key. However, I cannot get it to work and I can't tell if I have the incorrect cell selected or an incorrect textfield selected.

I am setting my tag in the cellForRowAtIndexPath with the following..

cell.tag = ((indexPath.section + 1) * 10) + indexPath.row;

this will create a tag with the tens place being a section value and the ones place being the row value. ie. tag 11 is section 0 row 1.

here is the code for my textFieldShould Return

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

[textField resignFirstResponder];

UITableViewCell *cell = (UITableViewCell *)textField.superview;
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];

cell = [self tableView:_tableView cellForRowAtIndexPath:indexPath];

if (indexPath.section == 0)
{
    if (indexPath.row == 0)
    {
        [[cell viewWithTag:((indexPath.section + 1) * 10) + (indexPath.row + 1)] becomeFirstResponder];
    }
    if (indexPath.row == 1)
    {
        [[cell viewWithTag:((indexPath.section + 2) * 10)] becomeFirstResponder];
    }
}
return YES;
}

One final note, currently the increments for the new tag are hardcoded, but I would like to be able to go to the new tag without hardcoding the actual value every time. Is this possible?

Upvotes: 0

Views: 1494

Answers (2)

Rajneesh071
Rajneesh071

Reputation: 31081

Set tag to your textField instead of cell.

yourTextField.tag = ((indexPath.section + 1) * 10) + indexPath.row;

Upvotes: 1

John Sauer
John Sauer

Reputation: 4421

If all of your cells contained 1 UITextField, I'd say you could subclass UITableViewCell and add a property that references the cell's text field, like I did here.

But you said that only some of your cells contain a text field, so another option would be to create an array of pointers to the UITextFields (I got the idea here). Then the user pressing Return would cycle through them like this:

- (BOOL) textFieldShouldReturn:(UITextField*)textField {
    NSUInteger currentIndex = [arrayOfTextFields indexOfObject:textField] ;
    if ( currentIndex < arrayOfTextFields.count ) {
        UITextField* nextTextField = (UITextField*)arrayOfTextFields[currentIndex+1] ;
        [nextTextField becomeFirstResponder] ;
    }
    else {
        [textField resignFirstResponder] ;
    }
}

Upvotes: 3

Related Questions