Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 566
some_id Avatar asked Feb 24 '23 02:02

some_id


2 Answers

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!

like image 66
PengOne Avatar answered Feb 28 '23 21:02

PengOne


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.

like image 41
Deepak Danduprolu Avatar answered Feb 28 '23 20:02

Deepak Danduprolu