Search code examples
swiftuitextfielduikit

Get returnKeyType text for UITextField


I am creating a custom UIToolBar to add as inputAccessoryView to a UITextField, I would like to add a UIBarButtonItem on the right side of this toolbar to serve as the return key of this textfield, and the text of this barButtonItem should be the same as the keyboard of that textfield.

My approach was:

        let buttonDone =  UIBarButtonItem(title: myTextField.returnKeyType, style: .done, target: self, action: #selector(pickerDone)

        let space = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)

        // toolbar
        let toolBar = UIToolbar()
        toolBar.barStyle = .default
        toolBar.items = [space, buttonDone]
        toolBar.sizeToFit()

        // setup input
        myTextField.inputAccessoryView = toolBar

But with this i get this error:

Cannot convert value of type 'UIReturnKeyType?' to expected argument type 'String?'

So, I try something like:

title: myTextField.returnKeyType.text

But returnKeyType doesn't has a .text variable or similar...

Is there any way of doing this? Should I go another way?


Solution

  • There is no built-in way to convert the UIReturnKeyType enum to a string. You will need to write your own code using a switch on the all the possible values.

    Here's one solution using an extension. Add support for the other values as needed.

    extension UIReturnKeyType {
        var label: String {
            switch self {
            case .default:
                return "Return"
            case .go:
                return "Go"
            case .done:
                return "Done"
            default:
                return "Enter"
            }
        }
    }
    

    Then you can use this as:

    let buttonDone =  UIBarButtonItem(title: myTextField.returnKeyType.label, style: .done, target: self, action: #selector(pickerDone)