0

I tried to add a toolbar for my UITextFiled, the keyboard is set to numpad. It is working but the button is not showing. I created an extension for my UITextfield

extension UITextField {

/// Adding a done button on the keyboard
func addDoneButtonOnKeyboard() {
    let doneToolbar = UIToolbar(frame: CGRect(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(title: "Done", style: .done, target: self, action: #selector(self.doneButtonAction))

    let items = [flexSpace, done]
    doneToolbar.items = items
    doneToolbar.sizeToFit()

    self.inputAccessoryView = doneToolbar
}

/// Done button callback
@objc func doneButtonAction() {
    self.resignFirstResponder()
}

}

and then I am calling this extension like this

private lazy var fromInputField: CoinpassInput = {
        let input = CoinpassInput()
        input.keyboardType = .decimalPad
        input.addTarget(self, action: #selector(fromInputFieldDidChange), for: .editingChanged)
        input.addDoneButtonOnKeyboard()
        return input
    }()

the toolbar is showing and working but the 'done; button is not showing. If I click on the right corner of the toolbar. the keyboard will hide. I dont know what I am missing why the button is not showing.

enter image description here

SadDeveloper
  • 107
  • 7

1 Answers1

0

Try this code, with slight modifications:

func addDoneButtonOnKeyboard() {
    let doneToolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50))
    doneToolbar.barStyle = .default
    doneToolbar.barTintColor = .red

    let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
    let done = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(self.doneButtonAction))
    done.tintColor = .yellow

    doneToolbar.setItems([flexSpace,done], animated: false)
    doneToolbar.isUserInteractionEnabled = true

    self.inputAccessoryView = doneToolbar
}
Mr.SwiftOak
  • 1,469
  • 3
  • 8
  • 19