I'm trying to use the below NumberFormatter
but can't figure out how to use it in a Text
view? Everything online relates to a TextView
.
static let numberFormat: NumberFormatter = {
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .none
numberFormatter.positivePrefix = "+"
numberFormatter.negativePrefix = "-"
return numberFormatter
}()
My attempted usage: but I am getting the error Instance method 'appendInterpolation(_:formatter:)' requires that 'Int' inherit from 'NSObject'
Text("\(450, formatter: Self.numberFormat)")
Here is a simple way:
With this way, you would keep your
@State
as clean as possible. Also, theformatterFunction(number: Int)
is reusable now and accessible from everywhere in comparison to your way, which would not be reusable or accessible.If you just want to add + and - to your Text, then use simply this function below: