|
I'm trying to create a TextField for a number that has an initial value of 0 but I do not want the text field to show any value unless it is higher than 0.
This technically works but then the user has to delete the '0' value from the field to enter a different value. I tried using an optional value instead but it seems like NumberFormatter doesn't work with optional values. Finally, I tried using an empty string instead but of course that won't work with NumberFormatter either. Is this a SwiftUI limitation or am I doing something wrong? Thanks! |
|
Minus 100 points to Hufflepuff for using the name In this article Formatting a Textfield for Numbers @twostraws notes it's a bit limited in what it can do. Additionally, I see you define quantity as an Integer. ( A user might enter 4.32, but when they hit return, the value will be 4. Just 4. Change your body to this to validate:
|
|
Have you tried adding this property to your
|
|
Luc asks:
Whenever I ask this question, the answer almost every time, is Yes! Then I ask myself, "Self? Am I the first programmer on the planet who has asked this question." And I know I'm not clever enough to be the first. Someone, somewhere has already asked and solved this question. So my next question is usually, "What would @twostraws do in this situation?" And he's answered this plenty of times! He looks in the documentation. So, no this isn't a SwiftUI limitation. But where you erred was in not reading the rest of the documentaton. You added .numberStyle, .minimumFractionDigits, and .maximumFractionDigits to your number formatter. (Frankly, not sure why you added those three, because your variable is an But a bit further down in the documenation, you'll find a section named "Configuring Numeric Symbols". There you'll scroll down and finally find:
If you don't want your users to see a 0, then ask NumberFormatter to substitute an empty string! Paste this code into Playgrounds.
|
|
Success! Thanks for the suggestion! :) |
|
|
|
|
|
Hi, first of all, thanks for this solution. Has helped me understand (and fix) the issue a lot. Unfortunately, in my case one issue seems to remain, though: I need my users to be able to enter a "0", but with this line:
they can't as the "0" immediately get's replaced by the placeholder text . Is there any workaround so that the user get's shown the placeholder String while no value is entered but can also enter a zero? Many thanks in advance! |
SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.
Sponsor Hacking with Swift and reach the world's largest Swift community!
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.
Link copied to your pasteboard.