In this tech-blog, I'll explain how to show a keyboard with done button.
Step 1.
Put following class in your project.
It will work with both TextField & TextView
class KeyboardDoneToolBar: UIView {
var textField: UITextField? = nil
var textView: UITextView? = nil
func getToolbar(_ width: Double) -> UIToolbar {
let toolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: width, height: 44))
let done = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(hideKeyboard))
let space = UIBarButtonItem(systemItem: .flexibleSpace)
toolbar.setItems([space, done], animated: false)
return toolbar
}
func setupWith(_ textField: UITextField) {
textField.inputAccessoryView = getToolbar(UIScreen.main.bounds.width)
self.textField = textField
}
func setupWithTextView(_ textView: UITextView) {
textView.inputAccessoryView = getToolbar(UIScreen.main.bounds.width)
self.textView = textView
}
@objc func hideKeyboard() {
textField?.resignFirstResponder()
textView?.resignFirstResponder()
}
}
Step 2.
Wire it with your input field
let toolbar = KeyboardDoneToolBar()
toolbar.setupWith(textField)
You're all set.
Here is how it's gonna look like.
Cheers
Have a good one