NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

How to format a TextField for numbers

Paul Hudson    @twostraws   

Updated for Xcode 12.5

You can attach a formatter to SwiftUI’s TextField in order to restrict what kind of data it can contain, but honestly it’s pretty limited in what it can do.

To demonstrate the functionality – and also its limitations – we could write some code to let the user enter a score in a game, and show what they entered. This is done by creating a NumberFormatter that formats its data as a decimal number, and attaching that to a TextField bound to an integer.

Here’s the code:

struct ContentView: View {
    @State private var score = 0

    let formatter: NumberFormatter = {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        return formatter
    }()

    var body: some View {
        VStack {
            TextField("Amount to transfer", value: $score, formatter: formatter)
                .textFieldStyle(RoundedBorderTextFieldStyle())
                .padding()

            Text("Your score was \(score).")
        }
    }
}

If you try using that you’ll notice a few things:

  1. The “Your score was” text view updates only when the user presses Return.
  2. The user is free to enter any kind of text that they want, and it only jumps back to being a number when they press Return.
  3. They can even enter invalid numbers, such as 12.34.56.

If you’re happy with that – if you’re happy that the text field allows any input, and only validates its numbers and updates its state when the user presses Return – then you’re good to go.

However, if you want to try to fix some those you’ll soon hit more problems. For example, you might try to attach the .keyboardType(.decimalPad) modifier to your text field in order to restrict it to numbers and decimal point only. However, now:

  1. The user can still enter multiple decimal points.
  2. There is no Return key to hide the keyboard or update the state.
  3. Even if you try and force keyboard dismissal using UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil) it still won’t work because the state won’t be updated – it’s as if the user typed nothing.

I wish there were a nice workaround for this, but I’m afraid there is not – not without rolling your own wrapper around UITextField, that is. In the meantime, you either accept the shortcomings of the existing functionality, or use an alternative input mechanism such as Stepper.

Hacking with Swift is sponsored by Emerge

SPONSORED Emerge helps iOS devs write better, smaller apps by profiling binary size on each pull request and surfacing insights and suggestions. Companies using Emerge have reduced the size of their apps by up to 50% in just the first day. Built by a team with years of experience reducing app size at Airbnb.

Set up a demo!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.