2

I would like my iOS SwiftUI TextField to display the placeholder "Enter an integer:", but the TextField displays 0 (the value of the var value). The placeholder "Enter an integer:" does appear when the user deletes the 0. How can I get the placeholder "Enter an integer:" to appear without making the user delete the 0 first? Thank you in advance. Xcode 11.6 on macOS Catalina 10.15.6.

struct ContentView: View {
    @State private var value: Int = 0;
    @State private var text: String = "";
    
    var body: some View {
        VStack {
            TextField(
                "Enter an integer:",
                value: $value,
                formatter: NumberFormatter(),
                onCommit: {self.text = "The product is \(2 * self.value).";}
            )
            .keyboardType(.numbersAndPunctuation)
            .textFieldStyle(RoundedBorderTextFieldStyle())
            
            Text(text)
        }
        .padding([.leading, .trailing], 16)
    }
}

2 Answers 2

5

We need to use formatter to show placeholder.

Our formatter should have formatter.zeroSymbol = ""

let numberFormatter: NumberFormatter = {
    let formatter = NumberFormatter()
    formatter.numberStyle = .none
    formatter.zeroSymbol  = ""
    return formatter
}()

Using formatted:

TextField("Enter an integer:", value: $value, formatter: numberFormatter)
                    .keyboardType(.numbersAndPunctuation)

Happy Coding :)

Sign up to request clarification or add additional context in comments.

Comments

3

To give placeholder with formatted TextField we need to use optional value holder.

Here is a fixed variant

demo

struct ContentView: View {
    @State private var value: Int?
    @State private var text: String = ""

    var body: some View {
        VStack {
            TextField(
                "Enter an integer:",
                value: $value,
                formatter: NumberFormatter(),
                onCommit: {self.text = "The product is \(2 * (self.value ?? 0)).";}
            )
            .keyboardType(.numbersAndPunctuation)
            .textFieldStyle(RoundedBorderTextFieldStyle())

            Text(text)
        }
        .padding([.leading, .trailing], 16)
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.