How to add Done button to the keyboard?

IosIphoneObjective CXcodeProgrammatically Created

Ios Problem Overview


UPDATE:

I also tried implementing UITextViewDelegate delegate and then doing in my controller:

- (BOOL)textViewShouldEndEditing:(UITextView *)textView
{
    [textView resignFirstResponder];
    return YES;
}

I also set the delegate of the text view to be self (controller view instance).

Clicking the Done button still inserts just a new line :(


UPDATE:

What I have done so far. I have implemented a UITextFieldDelegate by my view controller.

I have connected the text view to the view controller via outlet.

Then I did:


self.myTextView.delegate = self;

And:

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
	[textField resignFirstResponder];
	return YES;
}

But when I click on Done button, it just adds a new line.

So I have a UITextView element on my scene and when a user taps it, keyboard appears and it can be edited.

However, I cannot dismiss the keyboard.

How can I add Done button to the keyboard so it can be dismissed?

Ios Solutions


Solution 1 - Ios

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;
}

Solution 2 - Ios

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.

Solution 3 - Ios

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)
  }

Solution 4 - Ios

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
    }
}

Solution 5 - Ios

Set the 'Return Key' option under the text field option in the inspector for your text field. Then right click on the text field and while holding CTRL select 'Did End On Exit' and drag this into your view controllers file. This will create an IBAction method. Give the method a name and then enter the following values:

[textField becomeFirstResponder];
[textField resignFirstResponder];

Your method should look like this:

- (IBAction)methodName:(id)sender;
{
    [sender becomeFirstResponder];
    [sender resignFirstResponder];
}

Solution 6 - Ios

Ok, so I too have been struggling with this very issue. Currently I am accessing a UITextView in a UITableViewCell (via Tags). Because I am using prototype cells I cannot use IBActions nor IBOutlets like everyone suggests. Instead, I am using;

> -(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text

This will then provide me with the text each time the user hits a button. My solution then, was to get the ascii character for new line; "/n". If that is the text that was entered, I would resign the first responder. For example;

> // If the text length is 0 then the user is deleting something, so only check the ascii character if there is text to check if (text.length != 0) { // Get the Ascii character int asciiCode = [text characterAtIndex:0]; // If the ascii code is /n or new line, then resign first responder if (asciiCode == 10) { [alertTextView resignFirstResponder]; [DeviceTextView resignFirstResponder]; } }

Not sure if anyone else will need this hacky solution but I figured I'd put it out there in case someone needs it!

Solution 7 - Ios

This is best way to add Done Button on keyboard

textField.returnKeyType = UIReturnKeyDone;

Solution 8 - Ios

The following is my approach, in Swift 3. When the doneBtn clicked, let it send .editingDidEndOnExit event. I use this event to handle focus problem between multiple textFields.

// My customized UITextField
class MyTextField: UITextField {

    override func awakeFromNib() {
        super.awakeFromNib()
    
        // Add toolBar when keyboardType in this set. 
        let set : [UIKeyboardType] = [.numberPad, .phonePad]
        if (set.contains(self.keyboardType) ) {
            self.addDoneToolbar()
        }
    }

    // Add a toolbar with a `Done` button
    func addDoneToolbar() {

        let toolbar = UIToolbar()
        let space = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil)
        let doneBtn = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(onToolBarDone))
        
        toolbar.items = [space, doneBtn]
        toolbar.sizeToFit()
        
        self.inputAccessoryView = toolbar
    }
    
    @objc func onToolBarDone() {
        // I use `editingDidEndOnExit` to simulate the `Done` behavior 
        // on the original keyboard.
        self.sendActions(for: .editingDidEndOnExit)
    }
}

Solution 9 - Ios

In Interface Builder on the properties of the textView you can set the return button type to Done.

Then you need to check for when the Return button is pressed using

  - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text

Check if the text == "/n" then dismiss the keyboard by resigning first responder on your textView.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRichard KnopView Question on Stackoverflow
Solution 1 - IosSebastian FlückigerView Answer on Stackoverflow
Solution 2 - IosMike ZView Answer on Stackoverflow
Solution 3 - IosViJay AvhadView Answer on Stackoverflow
Solution 4 - IosEsqarrouthView Answer on Stackoverflow
Solution 5 - IosGarreth GoldingView Answer on Stackoverflow
Solution 6 - IosDonato PercontiView Answer on Stackoverflow
Solution 7 - IosDURGESHView Answer on Stackoverflow
Solution 8 - IosAechoLiuView Answer on Stackoverflow
Solution 9 - IosRyan PoolosView Answer on Stackoverflow