The easiest way to dismiss keyboard UITextView Swift

For UITextView there is no Done button to dismiss the keyboard like UITextField. UITextView is having a return button on the keyboard for the new line. The keyboard return button is used for the new line but a lot of developers use this to dismiss keyboard using its delegate function which is wrong.
The best way is to add a done button over the keyboard to dismiss it. We will do this using UITextView Extension so you only need to write just one line of code to achieve this.
1: Create a new project or use your existing project.
2: Drag and drop a UITextView and create an IBOutlet of it in your Nib file
Now your ViewController class will look like below
class ViewController: UIViewController {
    
    @IBOutlet weak var myTextView: UITextView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
}

Adding UITextView Extension

Create a new swift file and name it UITextView+Additions or whatever you like

Add below code in this file
import UIKit

extension UITextView {
    
    func addDoneButton(title: String, target: Any, selector: Selector) {
        
        let toolBar = UIToolbar(frame: CGRect(x: 0.0,
                                              y: 0.0,
                                              width: UIScreen.main.bounds.size.width,
                                              height: 44.0))//1
        let flexible = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)//2
        let barButton = UIBarButtonItem(title: title, style: .plain, target: target, action: selector)//3
        toolBar.setItems([flexible, barButton], animated: false)//4
        self.inputAccessoryView = toolBar//5
    }
}
1: Create a UIToolbar
2: Create a UIBarButtonItem of type flexibleSpace
3: Create UIBarButtonItem using parameter title, target and action
4: Assign this two UIBarButtonItem to toolBar
5: Set this toolBar as inputAccessoryView to the UITextView

Move to ViewController class

Now let’s add a Done button using the above extension class. Make below changes in your ViewController class.
class ViewController: UIViewController {
    
    @IBOutlet weak var myTextView: UITextView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 1
        self.myTextView.addDoneButton(title: "Done", target: self, selector: #selector(tapDone(sender:)))
    }
    
    // 2
    @objc func tapDone(sender: Any) {
        self.view.endEditing(true)
    }    
}

Now run your code.

Read our next Article: Very Simple Expand Collapse UITableView Swift

1 comment on “The easiest way to dismiss keyboard UITextView Swift

Leave a Reply

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