Luc asks:
Is this a SwiftUI limitation or am I doing something wrong?
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 Integer
!)
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:
var zeroSymbol: String?
The string used to represent a zero value.
If you don't want your users to see a 0, then ask NumberFormatter to substitute an empty string!
Paste this code into Playgrounds.
// Fun with NumberFormatter
// For: @lvandal
// By: Obelix 2022.02.03
// Paste into Playgrounds
import SwiftUI
import PlaygroundSupport
struct FunWithNumberFormat: View {
@State private var quantity = -500 // change this number a few times
// Computed variable for testing
var formattedLucNumber : String {
Formatter.lucNumberFormat.string(from: NSNumber(value: quantity))!
}
var body: some View {
VStack {
Text("Fun with NumberFormatter").font(.body)
TextField("Quantity", value: $quantity, formatter: Formatter.lucNumberFormat)
.textFieldStyle(.roundedBorder)
.frame(width: 200).padding()
Text( "raw quantity: \(quantity)").padding(.bottom)
Text( "formatted: \(formattedLucNumber)")
}
}
}
// This is a reusable number formatter
extension Formatter {
static let lucNumberFormat: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .none
formatter.minusSign = "👺 " // Just for fun!
formatter.zeroSymbol = "" // Show empty string instead of zero
return formatter
}()
}
// Click to play in Playgrounds.
PlaygroundPage.current.setLiveView( FunWithNumberFormat().frame(width: 400, height: 300) )