0

I have a UITableView with sections where when you tap on a section, the section expands and there are options to choose from or you can insert your own option via a UITextField in one of the UITableViewCells. For that cell, I have this code in tableView: cellForRowAtIndexPath: to configure the custom cell and set the first responder.

        DataAddTVCell *dataInputcell = (DataAddTVCell *)cell;
        dataInputcell.data.delegate = self;
        self.dataTextfield = dataInputcell.data;
        [self.dataTextfield becomeFirstResponder];

the data field is the UITextField. I save the UITextField in self.dataTextField so that I can resignFirstResponder later.

The first time my DataAddTVCell is loaded from and expanded section, it works fine and becomes the first responder. Resigning as first responder also works. But when the cell is loaded again when another section is expanded, it doesn't become the first responder. If I tap on the textField, the keyboard shows up fine and I can resign the first responder in the same way I did before. Not sure why the textField can only become the first responder once. I also have these delegate methods and have set <UITextFieldDelegate>

- (BOOL)canBecomeFirstResponder
{
    return YES;
}

- (BOOL)becomeFirstResponder
{
    return YES;
}

I'm suspecting that this is happening because I am using dequeueReusableCellWithIdentifier. Is there any way to make it work while using this? Or will I have to create a new cell every time if I want it to become the first responder always when it shows? That seems pretty bad to create so many cells always though.

Kanhaiya Sharma
  • 1,040
  • 8
  • 20
user1529956
  • 695
  • 2
  • 10
  • 21

1 Answers1

0

This is happening because every time cell is loaded, it is recreated and so its subviews. As a result, reference to your textfield is lost. To resign it successfully, you need to keep focus the parent cell in order to avoid re-creation of cell.

EDIT

Another alternate is that you remember the indexpath of cell, who's textfield you want to becomefirstresponder. When creating cell at that indexpath, iterate through its subviews, catch the reference of textfield and call becomeFirstResponder on it.

You need to do the same thing I mentioned above. In cellForRowAtIndexPath: write following code at appropriate place:

 if(indexPath.section == 0)//your section in which that cell is present. e.g. 0
            {
                if(indexPath.row == 1)//cell no. 1
                {
                    if(showingInputCell)//flag to keep track either it is textfield cell or other
                    {
                        for (UIView * subview in cell.subviews) {
                            if([subview isKindOfClass:[UITextField class]])
                                [(UITextField *)subview becomeFirstResponder];
                        }
                    }
                }
            }
NightFury
  • 12,692
  • 6
  • 65
  • 112