How to get UITextField from inputAccessoryView button click
ios, objective-c, uitextfield, uitoolbar
Solution
You can keep track of the currently focused `UITextField` in a variable, and use that variable in your `inputAccesoryView` method:
in your .h file: make sure you're conforming to the `UITextFieldDelegate` protocol:
@interface MyViewController : UIViewController <UITextFieldDelegate>
and add this property:
@property (assign, nonatomic) UITextField *activeTextField;
In your .m file: While creating your dynamic textfields:
...
theTextField.delegate=self;
...
And add these implementations of the `UITextFieldDelegate` protocol:
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
self.activeTextField = textField;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
self.activeTextField = nil;
}
And now, in the method invoked by your `inputAccesoryView`:
- (void)navigationBarDoneButtonPressed:(id)sender{//Just an example
self.activeTextField.text=@"Test";
}
Problem
I have a dynamic number of `UITextFields` which all have an `inputAccessoryView`. This is composed of a `UIToolbar` which has a button on it. When this button is pressed it calls a method, however, within this method I somehow need the ability to access the underlying `UITextField`. Please could someone advise how this is possible? ``` // Create the toolbar controls UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(navigationBarDoneButtonPressed:)]; UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]; // Setup the toolbar navigationToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(10.0, 0.0, 310.0, 40.0)]; [navigationToolbar setItems:@[flexibleSpace, doneButton]]; // In a UITableView I create a number of cells which contain UITextFields.... // This is the method that gets called when a user presses the done button - (void)navigationBarDoneButtonPressed:(id)sender { NSLog(@"Based on sender I need to access the underlying UITextField."); } ```