1

I have a UIToolbar that I'm adding as an inputAccessoryView to three UITextFields with numeric keypads. On this UIToolbar I have a cancel and a done button to dismiss the keyboard as per this post: trying to add done button to Numeric keyboard. This works great for one UITextField, which can be easily identified. However, I'm trying to use the same code for three UITextFields. Here's what I have:

- (void) viewDidLoad
{
    [super viewDidLoad];

    // weight, numberOfDrinks, and drinkingDuration are UITextFields set up in Storyboard.
    // I implemented the UITextFieldDelegate protocol in the .h file and set the UITextField's delegates to the owning ViewController in Storyboard.

    self.weight.delegate = self;
    self.numberOfDrinks.delegate = self;
    self.drinkingDuration.delegate = self;
}

- (void) textFieldDidBeginEditing:(UITextField *)textField {

    UIToolbar *doneToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
    doneToolbar.barStyle = UIBarStyleBlackTranslucent;

    // I can't pass the textField as a parameter into an @selector
    doneToolbar.items = [NSArray arrayWithObjects:
                         [[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonItemStyleBordered target:self action:@selector(cancelKeyboard:)],
                         [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
                         [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(doneWithKeyboard:)],
                         nil];

    [doneToolbar sizeToFit];

    textField.inputAccessoryView = doneToolbar;
}

- (void) cancelKeyboard: (UITextField *) textField {

    textField.text = @"";

    [textField resignFirstResponder];
}

- (void) doneWithKeyboard: (UITextField *) textField {

    [textField resignFirstResponder];
}

I get an "unrecognized selector sent to instance" error because the cancelKeyboard and doneWithKeyboard methods aren't being passed the textField parameter they need. Any ideas how to implement this properly?

Thanks!

Ben

Community
  • 1
  • 1
Benjamin Martin
  • 1,795
  • 3
  • 15
  • 17

2 Answers2

1

use globle object in .h file UITextField *SelectedTextField; // In did begin editing method define SelectedTextField = textField; Then use it on your method to resign or show.

It would help for you.

1

If you just want to dismiss the keyboard in the current view controller, you can call the endEditing method of the view property of the view controller:

[self.view endEditing];
Valent Richie
  • 5,226
  • 1
  • 20
  • 21
  • Very cool I did not know about this! It doesn't allow me to reverse a `UITextField`'s state when I hit the cancel button, but I'm glad to know this exists. – Benjamin Martin Jun 12 '13 at 19:15