How to add a ‘Done’ button to a numberPad in Swift

The best way to add a ‘Done‘ button to a numberPad, which doesn’t have it by default,  is to extend UITextField. Three steps:

1. set the keyboard type for your UITextField in your viewController subclass:

e.g. myTextField.keyboardType = UIKeyboardType.numberPad

2. save the code below the line as  ‘UITextField+Extensions.swift’ and add to your project.

3. After this, if you select any UITextField in the storyboard editor, there will be a new item under the ‘Attributes Inspector’ for that UITextField, where you can set ‘Done Access…’ On, Off or default. Choose ‘On’ if you want the ‘Done’ button to show up.

import Foundation

import UIKit

extension UITextField{

       @IBInspectable var doneAccessory: Bool{


            return self.doneAccessory


        set (hasDone) {

            if hasDone{






    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



        self.inputAccessoryView = doneToolbar



    @objc func doneButtonAction()





Leave a Reply

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

The reCAPTCHA verification period has expired. Please reload the page.