macosswiftuitextfield

TextField force uppercased while typing (macOS)


How do I force uppercase characters while typing in a TextField on macOS?

I started with this snippet from Paul Hudson:

struct ContentView: View {
    @State private var name = "Paul"

    var body: some View {
        TextField("Shout your name at me", text: $name)
            .textFieldStyle(.roundedBorder)
            .textCase(.uppercase)
            .padding(.horizontal)
    }
}

That doesn't work, typed characters still show as lowercase. Also I tried the accepted answer here (using $0.uppercased() instead of $0.lowercased())

https://stackoverflow.com/a/60969666/1015258

Also, same thing, text is still shown as lowercase.

What am I missing?


Solution

  • I am using onChange in my project for uppercase only text fields

    .onChange(of: name) { old, new in
         guard old != new else { return }
         name = new.uppercased()
    }