top of page

SwiftUI TextField with Numbers Only

  • Writer: Troy Husted
    Troy Husted
  • Oct 21, 2024
  • 2 min read

SwiftUI allows for tons of customizations with textfields - whether it be a custom formatter for strings, or in this case a native formatter for numbers.


Traditionally, a TextField for a string could be setup like this:

struct StringsAndNumbersTextField: View {

    @State private var inputText: String = ""

    

    var body: some View {

        VStack {

            TextField("Placeholder text", text: $inputText)

        }

        .padding()

    }

}

Thankfully, SwiftUI supports a native way to change this from accepting strings to just numbers. We'll go ahead and change the inputText variable from a String to a Double. In doing this, we'll have to edit our TextField slightly to instead hold a value, and have a format.

struct StringsAndNumbersTextField: View {

    @State private var inputText: Double?

    

    var body: some View {

        VStack {

            TextField("Placeholder text", value: $inputText, format: .number)

        }

        .padding()

    }

}

Just like that, our TextField now holds just numbers! Note, we use an optional Double to allow for the placeholder text to show up. By setting the inputText to a non-optional, we'd never see that placeholder.


To prevent users from being able to input any regular characters (and limit them to just numbers), we can add a modifier onto our TextField to only allow the keyboard to be a number pad.

import SwiftUI


struct StringsAndNumbersTextField: View {

    @State private var inputText: Double?

    

    var body: some View {

        VStack {

            TextField("Placeholder text", value: $inputText, format: .number)

                .keyboardType(.numberPad)

        }

        .padding()

    }

}


#Preview {

    StringsAndNumbersTextField()

}


Just like that, your TextField is now set up to handle numbers with no extra boilerplate needed!

Recent Posts

See All
SwiftUI Custom Units / Dimensions

Creating custom Units and Dimensions in SwiftUI is super easy. In this tutorial, we use the UnitMomentum as an example for setting these up.

 
 
 

Comments


bottom of page