BLACK FRIDAY: Save 50% on all my Swift books and bundles! >>

Textfield day 35

Forums > 100 Days of SwiftUI

I'm two days into day 35 and I can't find a solution to my problem. A part of my code

    @State private var userAnwser = 0
    @FocusState private var userAnwserFocus: Bool
TextField("Answer", value: $userAnwser, format: .number)
                                .textFieldStyle(.roundedBorder)
                                .keyboardType(.decimalPad)
                                .focused($userAnwserFocus)

When running this code the textfield contains the 0. I guess that is normal because of the 'userAnwser'. But it is not gray, and when I click on it to enter a number (or when I start entering a number), the 0 doesn't autmaticaly removes it self. With the weSplitt it happend aswel if I remember corretly. I would hope that 'Answer' would be in the textfield instead of the 0. With searching the web I'm mainly finding soluitons for when you use a String, but I don't have a String. Is it possible to have a text as placeholder (I think it is called that?) when a user needs to enter a number? And how to clear the placeholder if the user starts to enter text? If I remove the 0 myself, I do see 'Answer' in gray. untill I hide the keyboard and then it is the 0 (or other last know value from 'userAnwser')

2      

@Bnerd  

Then make it a String and change it to Int before you use it ;)

2      

The problem is that when your view is initialized you are setting user answer to zero.

@State private var userAnwser = 0

The "Answer" text will only show in the TextField if there is no text value currently stored in it. But, since it already has a zero right when the view loads, it won't show unless you manually delete the zero from it. When you are working with a String in a TextField it is easier, because you can simply initialize the string to an empty string when you first create it.

@State private var userAnswerString = ""

Then it would be empty when it first appears and your label would show instead. But it is a little trickier to do when you are working with a number in the text field instead.

In the "We Split" app I got around the issue of having no label on the TextField by putting it into a Section, and adding a header to the Section like this...

Section {
  TextField("Enter an Amount", value: $checkAmount, format: .currency(code: Locale.current.currencyCode ?? "USD"))
    .keyboardType(.decimalPad)
    .focused($amountIsFocused)
} header: {
  Text("Check Amount")
}

But the problem of having to manually delete the zeroes before entering your own values still exists that way.

There is probably a more correct way to do this that involves adding an .onTapGesture modifier to the TextField to automatically remove the text when the user taps on it. But I just moved on with the lesson plan after getting the app to work and figured that I would learn more about that kind of thing later.

2      

i think you misspelled your variable name. Doesnt actually affect code but i think its unintentional.

  @State private var userAnwser = 0

should be

  @State private var userAnswer = 0

2      

@Bnerd  

Ok I found a quick way... Step : 1 Make a new file with an observable Class with an optional Int variable. Example:

class myInt: ObservableObject {
    @Published var myInt: Int?
}

In your content view make an instance of your class and bind the TextField with the optional Int, Voila, no more initial value! Example:

@StateObject var myIntXXX =  myInt()

    var body: some View {
        Form {
            TextField("Add here", value: $myIntXXX.myInt, format: .number)
            }
        }

If you want to remove even the placeholder adjust as per below the following:

@StateObject var myIntXXX =  myInt()
    @State private var myPlaceholder = "Add Here"

    var body: some View {
        Form {
            TextField("\(myPlaceholder)", value: $myIntXXX.myInt, format: .number).onTapGesture {
                myPlaceholder = ""
            }
            }
        }

2      

@Fly0strich in the weSplitt is still excist, and it doesn't really mathers. For the math game it is pretty annoying I think.

@Nanometer54 In my reall code I even made a other mistake on the word. I thought I wrote it right here. But there is no spellcheck on this typing area.

@Bnerd Thankyou for looking into this. I will look into your solluiton later to see how that works.

2      

I found a solution. I don't know if this is somehow wrong some where but for now:

    @State private var userAnser : Int?

Later on in the code in a function I have

 userAnser = nil

Now I see the "Answer" in the textfield and no more zero's that keep standing there.

2      

This is probably the best solution actually. I always kind of forget to think about how easily optional values can be used in Swift.

2      

@Bnerd  

I think your solution is the easiest and most efficient.

2      

Save 50% in my WWDC sale.

SAVE 50% All our books and bundles are half price for Black Friday, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.