Olex
Olex

Reputation: 1656

How to get textFields in custom UITableView

Very beginner obj-c question.

I have plain UITableView with two sections, but I am interested only in first section now. This section have four custom cells (inherited from standard UITableViewCell), and they have a UITextField's as a property.

I need to improve custom Input Accessory View with buttons "Next", "Previous"(for switch between textFields in tableview) and "Done" (dismissimg of keyboard). http://uaimage.com/image/62f08045

In -textFieldShouldReturn i set tags for textFields from 0 to 3. My next plan is to add textFields into NSMutableArray in -viewDidLoad and then just set and resign first responder for the textFields. Approximate code listing for "Next" button:

- (void) inputAccessoryViewDidSelectNext:(FDInputAccessoryView *)view {
    for (UITextField *textField in [self textFieldsArray]) {

        if ([textField isFirstResponder]) {

            [textField resignFirstResponder];
     UITextField *field = [[self textFieldsArray] objectAtIndex:textField.tag + 1];
            [field becomeFirstResponder];
        }

    }
}

Questions:

Sorry for the dumb questions, I am a very beginner.

Thanks, Alex.

Upvotes: 2

Views: 3041

Answers (1)

johngraham
johngraham

Reputation: 6490

I think you have the right idea, but a few things come to mind:

  • Just to be safe, don't start with tag number 0. Every view has a tag number defaulted to 0, so you may get something unexpected.
  • Don't set the text view's tags inside of the textFieldShouldReturn, set the tags in cellForRowAtIndexPath or viewDidLoad, wherever you init the textFields.
  • Add the textFields to the cell's contentView, not the cell itself.
  • You don't have to resign first responder from the first text field, you can just becomeFirstResponder on the new one.
  • Make sure you're handling the last text view edge case: You could loop around to the first text field or simply dismiss the keyboard at the end.

If you want to get the textField in the cell:

UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:
                         [NSIndexPath indexPathForRow:ROW_NUMBER inSection:1]];
UITextField *textField = (UITextField *)[cell.contentView viewWithTag:TEXT_FIELD_TAG];

Upvotes: 5

Related Questions