How to add Done button to the keyboard?
thats quite simple :)
[textField setReturnKeyType:UIReturnKeyDone];
for dismissing the keyboard implement the <UITextFieldDelegate>
protocol in your class, set
textfield.delegate = self;
and use
- (void)textFieldDidEndEditing:(UITextField *)textField {
[textField resignFirstResponder];
}
or
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return YES;
}
Go into your storyboard, select your text field and under the Attributes Inspector there is an option that says "return key"...select "Done".
Then go into your ViewController and add:
- (IBAction)dismissKeyboard:(id)sender;
{
[textField becomeFirstResponder];
[textField resignFirstResponder];
}
Then go back to your text field, click outlets and link "Did end on exit" to dismissKeyboard action.
Add UIToolBar as custom view that will have Done button as UIBarButtonItem in it.
This is safer and cleaner way to add Done button to any Type of Keyboard. Create UIToolBar add Done Button to it and set inputAccessoryView of any UITextField or UITextView.
UIToolbar *ViewForDoneButtonOnKeyboard = [[UIToolbar alloc] init];
[ViewForDoneButtonOnKeyboard sizeToFit];
UIBarButtonItem *btnDoneOnKeyboard = [[UIBarButtonItem alloc] initWithTitle:@"Done"
style:UIBarButtonItemStyleBordered target:self
action:@selector(doneBtnFromKeyboardClicked:)];
[ViewForDoneButtonOnKeyboard setItems:[NSArray arrayWithObjects:btnDoneOnKeyboard, nil]];
myTextField.inputAccessoryView = ViewForDoneButtonOnKeyboard;
IBAction For Done Button
- (IBAction)doneBtnFromKeyboardClicked:(id)sender
{
NSLog(@"Done Button Clicked.");
//Hide Keyboard by endEditing or Anything you want.
[self.view endEditing:YES];
}
SWIFT 3
var ViewForDoneButtonOnKeyboard = UIToolbar()
ViewForDoneButtonOnKeyboard.sizeToFit()
var btnDoneOnKeyboard = UIBarButtonItem(title: "Done", style: .bordered, target: self, action: #selector(self.doneBtnFromKeyboardClicked))
ViewForDoneButtonOnKeyboard.items = [btnDoneOnKeyboard]
myTextField.inputAccessoryView = ViewForDoneButtonOnKeyboard
Function
@IBAction func doneBtnFromKeyboardClicked (sender: Any) {
print("Done Button Clicked.")
//Hide Keyboard by endEditing or Anything you want.
self.view.endEditing(true)
}
Swift version:
In Your ViewController:
textField.returnKeyType = UIReturnKeyType.Done
textField.delegate = self
After your ViewController
extension MyViewController: UITextFieldDelegate {
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}