Question

SwiftUI TextField force lowercase

I would like to use a specific TextField for url entries where the user could only enter lowercase characters, but I can't find any TextField modifier for this purpose. Is there any solution?

 46  19354  46
1 Jan 1970

Solution

 97

TextField has a .autocapitalization() method.

You can use like this without custom binding:

TextField("URL", text: $url)
                    .keyboardType(.URL)
                    .autocapitalization(.none)

For iOS 15 SwiftUI have a new .textInputAutocapitalization() method:

.textInputAutocapitalization(.never)

This means that any text input by the user will be .lowercased()

2020-05-17

Solution

 19

You can create a custom binding and set your state URL variable to the lowercased version of the input through it:

struct ContentView: View {
    @State var url: String = ""

    var body: some View {
        let binding = Binding<String>(get: {
            self.url
        }, set: {
            self.url = $0.lowercased()
        })

        return VStack {
            TextField("Enter URL", text: binding)
        }

    }
}
2020-04-01