some_id
some_id

Reputation: 29896

Add a done button in a UINavigationbar

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.

Upvotes: 4

Views: 3191

Answers (2)

PengOne
PengOne

Reputation: 48398

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!

Upvotes: 6

Deepak Danduprolu
Deepak Danduprolu

Reputation: 44633

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.

Upvotes: 2

Related Questions