Swiftui: How to change the text and color of textfield keyboard return button

Viewed 1184

when working with Texfield in swiftui, Is it possible to customize the return button on keyboard that is activated when a user tap on the textfield. I want to change the color and have it say "Search". Here is a textfield code I'm using

       TextField("Search", text: $searchText, onCommit: show)
                     .foregroundColor(.primary)

how can I customize the keyboard return button?

3 Answers

1) Set the text "Search" to the Return key:

textField.returnKeyType= .search

As the Apple Documentations states: "Specifies that the visible title of the Return key is “Search”".

image

2) Change color of the Return key

There is no public API available for it.
You can do it in a hacky way with private API but you get no guarantee that in the future it will work and even then your app will be get rejected in app store review.

You can only customize the title and color of the return key, if you don't implement your own customized keyboard(which is a lot work).

For the title, you can customize it by:

textField.returnKeyType= .search

For the color, there are two options: blue (enabled) and gray (disabled). And you can customized it in a limited way:

textField.enablesReturnKeyAutomatically

The default value for this property is false. If you set it to true, the keyboard disables the Return key when the text entry area contains no text. As soon as the user enters some text, the Return key is automatically enabled.


In SwiftUI, unfortunately, there isn't any modifiers for these things currently. You might have to do it by wrapping UITextField yourself with UIViewRepresentalbe. The implementation is something like this:

struct SearchTextField: UIViewRepresentable {
    @Binding var searchText: String
    
    func makeUIView(context: Context) -> UITextField {
        let textField = UITextField()
        textField.placeholder = "Search"
        textField.returnKeyType = .google // or .search, .yahoo, etc.
        textField.enablesReturnKeyAutomatically = true
        textField.keyboardType = .webSearch
        // ... set other preferrences
        return textField
    }
    
    func updateUIView(_ textField: UITextField, context: Context) {
        //
    }
    
    // ...
}

For a more detailed implementation, check out this good SO answer.

Related