How does one add a done button to a UINavigationbar when the user touches a specific textfield or textview?
Or would a better way be to detect when the keyboard is showing, and then display the button.
I would like the done button to dismiss the keyboard like in standard Notes application.
You could try something similar to this:
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone
target:self
action:@selector(doneEditing)];
[[self navigationItem] setRightBarButtonItem:doneButton];
[doneButton release];
}
and also
- (void)textViewDidBeginEditing:(UITextView *)textView
{
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone
target:self
action:@selector(doneEditing)];
[[self navigationItem] setRightBarButtonItem:doneButton];
[doneButton release];
}
with the following customized as you like
- (void)doneEditing {
[[self view] endEditing:YES];
}
then remove the button in - (void)textFieldDidEndEditing:(UITextField *)textField
and also in - (void)textViewDidEndEditing:(UITextView *)textView
Just remember to set up the delegates!
You should adopt the delegate protocol as I believe you are at an advantage there. You can do this –
- (void)textViewDidBeginEditing:(UITextView *)textView {
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone
target:textView
action:@selector(resignFirstResponder)];
self.navigationItem.rightBarButtonItem = doneButton;
[doneButton release];
}
But if you were to observe the notification, you can't know which one is the first responder. Of course, it is not much of a problem if you have only one object to worry about.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With