SWIFT — Add keyboard Done button using UIToolbar
For one recent project that I was working on, I had to add a keyboard Done button. I have decided to create an extension that will be really easy to use, and I wanted to share it with you. The extension can be applied on UITextField or UITextView component.
This is a really common feature in almost all iOS apps, so it’s good to have a ready copy-paste solution. To achieve the adding of a keyboard Done button we need to use UIToolbar.
UIToolbar is a control that displays one or more buttons along the bottom edge of your interface.
To make things even simpler, I have added an @IBInspectable attribute. In other words, the inspectable will add a dropdown in the Interface Builder under the Attribute Inspector tab. Since the attribute inspector will be boolean, the options in the dropdown will be On/Off.
NOTE: This screenshot shows you more attributes, but you need to pay attention only to the Done Accessory.
How to add the Keyboard Done Button
import Foundation
import UIKitextension UITextField{
@IBInspectable var doneAccessory: Bool{
get{
return self.doneAccessory
}
set (hasDone) {
if hasDone{
addDoneButtonOnKeyboard()
}
}
}
func addDoneButtonOnKeyboard()
{
let doneToolbar: UIToolbar = UIToolbar(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50))
doneToolbar.barStyle = .default
let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let done: UIBarButtonItem = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(self.doneButtonAction))
let items = [flexSpace, done]
doneToolbar.items = items
doneToolbar.sizeToFit()
self.inputAccessoryView = doneToolbar
}
func doneButtonAction()
{
self.resignFirstResponder()
}
}
Create an extension called UITextField+Extensions.swift, and copy-paste this snippet above. I think that the snippet is self-explanatory, but I will walk you through the functions…
- addDoneKeyboardButton() — creates the keyboard done button using UIToolbar. Inside the toolbar, we create a UIBarButtonItem. You can name the button however you want, and you can add multiple buttons (depending on your needs). In other words, use this function to customize the toolbar.
- doneButtonAction() — this is a function that triggers when the user presses the keyboard Done button. In our case, the keyboard gets resigned.