UITextView: Add Done button in Keyboard

Recently I had a requirement to use UITextView, but as we know the return key of UITextView’s keyboard doesn’t dismiss the keyboard, instead it adds a new line.

So to dismiss the keyboard, I switched on the Done Accessory of UITextView and called resignFirstResponder().

Let the magic begin…

magic

Implementation:

Do following in your storyboard/xib:

Go to “Show Attributes Inspector” and make Done Accessory “on”

Create a Swift class UITextView+Extension.swift and add following code to it

import UIKit

// Usage: Switch UITextView's "Done Accessory" to ON
extension UITextView {
  
  @IBInspectable var doneAccessory: Bool {
    get{
      return self.doneAccessory
    }
    set (hasDone) {
      if hasDone{
        addDoneButtonInKeyboard()
      }
    }
  }
  
  func addDoneButtonInKeyboard() {
    let doneToolbar: UIToolbar = UIToolbar(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50))
    doneToolbar.barStyle = .default
    
    let flexSpaceBarButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
    let doneBarButton: UIBarButtonItem = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(self.doneButtonAction))
    
    let items = [flexSpaceBarButton, doneBarButton]
    doneToolbar.items = items
    doneToolbar.sizeToFit()
    
    self.inputAccessoryView = doneToolbar
  }
  
  @objc func doneButtonAction() {
    self.resignFirstResponder()
  }
}
easy

Output:

This is the final outcome

Explanation:

@IBInspectable: It inspects your interface builder’s attributes. In our case, “Done Accessory” attribute that we set in the interface builder. In above code, it will check if the Done Accessory is on, then it will call addDoneButtonInKeyboard() function. You can provide any title to done button.

addDoneButtonInKeyboard(): This function will add UIToolBar and UIBarButtonItem to the inputAccessoryView of UITextView

doneButtonAction(): This function is called on tapping the done button. In above code, it will resign the UITextView as first responder, i.e. UITextView will not be in focus.

Great thing is, you can use same trick with UITextField too. Just need to change to extension UITextField and it should do the work! Don’t forget to create a separate extension file for UITextField.

————————————————– END ————————————————–

3 thoughts on “UITextView: Add Done button in Keyboard

  1. Just wish to say your article is as surprising. The clearness in your publish is just excellent and
    that i can think you are a professional in this subject.

    Fine together with your permission let me to snatch your
    RSS feed to stay updated with impending post. Thank you 1,000,000 and please keep up the gratifying work.

Leave a Reply

Your email address will not be published. Required fields are marked *