SWIFT — Add keyboard Done button using UIToolbar

Dejan Atanasov
Swift2Go
Published in
3 min readJul 7, 2017

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 UIKit
extension 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.

That’s it from this tutorial and if it helped you please 👏 or share this story so others like you can find it. Thank you for your attention! 🚀

Check out my latest projects:

Read more of my writing on Medium:

Subscribe to my Newsletter:

--

--

Dejan Atanasov
Swift2Go

Senior iOS & Android Developer | Creator of Swift2Go | @hackernoon writer | Hire Me: http://bit.ly/2XfxbBR