SwiftUI TextField force lowercase
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)
}
}
}
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()
XCODE 13
SwiftUI - IOS 15.0
FROM:
.autocapitalization(.none)
TO:
.textInputAutocapitalization(.never)
Example:
TextField("Enter URL", text: $url)
.keyboardType(.URL)
.textInputAutocapitalization(.never)
if all you want is to "end up" with a lowercase string after the user press return, you could do this:
@State var txt: String = ""
var body: some View {
TextField("", text: $txt, onEditingChanged: { _ in
self.txt = self.txt.lowercased()
})
}