Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI TextField force lowercase

Tags:

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?

like image 416
Matias Masso Avatar asked Apr 01 '20 09:04

Matias Masso


People also ask

How do you make a TextField lowercase in SwiftUI?

SwiftUI's TextField view normally lets users write their text in whatever case they want, but if you want to control that you can force either uppercase or lowercase text using the textCase() modifier. Important: If you're using Xcode 12 you need to use RoundedBorderTextFieldStyle() rather than .

How do I create a secure TextField in SwiftUI?

You just make a View with all the code you want for the SecureTextField and the TextField then all you have to do is call the HybridTextField where ever you need it.

What is prompt in TextField SwiftUI?

SwiftUI's TextField supports placeholder text just like UITextField did – gray text that is shown in the text field when it's empty, either giving users a prompt (“Enter your password”) or showing some example data.


2 Answers

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()

like image 122
wmorgue Avatar answered Sep 30 '22 05:09

wmorgue


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)         }      } } 
like image 30
Vyacheslav Pukhanov Avatar answered Sep 30 '22 04:09

Vyacheslav Pukhanov