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.
精彩评论