Search code examples
iosswiftuitextfield

How can I show done button on the decimal pad keyboard?


I'm trying to learn Swift and I've done on the view screens. But as you can understand more easily by checking the screenshot, when I enter a value into a text field, there isn't any done button showing up so I can not hide the keyboard from the screen. And that makes it impossible to press the submit button which is located bottom of the screen view.

screenshoot while the keyboard is being shown

screenshoot while the keyboard is closed


Solution

  • Firstly, create a new Swift File. Add this to the file :

    import Foundation
    import UIKit
    
    extension UIViewController{
        func toolBar() -> UIToolbar{
            let toolBar = UIToolbar()
            toolBar.barStyle = .default
            toolBar.isTranslucent = true
            toolBar.barTintColor = UIColor.init(red: 0/255, green: 25/255, blue: 61/255, alpha: 1) //Write what you want for color
            let space = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
            var buttonTitle = "Done" //Or "Tamam"
            var cancelButtonTitle = "Cancel" //Or "İptal" for Turkish
            let doneButton = UIBarButtonItem(title: buttonTitle, style: .done, target: self, action: #selector(onClickDoneButton))
            let cancelButton = UIBarButtonItem(title: cancelButtonTitle, style: .plain, target: self, action: #selector(onClickCancelButton))
            doneButton.tintColor = .white
            cancelButton.tintColor = .white
            toolBar.setItems([cancelButton, space, doneButton], animated: false)
            toolBar.isUserInteractionEnabled = true
            toolBar.sizeToFit()
            return toolBar
        }
    
        @objc func onClickDoneButton(){
            view.endEditing(true)
        }
    
        @objc func onClickCancelButton(){
            view.endEditing(true)
        }
    }
    

    And add this toolbar to your textfield :

    yourTextField.inputAccessoryView = toolBar()
    

    Hope it helps...