简体   繁体   中英

How to use a NumberFormatter in SwiftUI?

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, the formatterFunction(number: Int) is reusable now and accessible from everywhere in comparison to your way, which would not be reusable or accessible.


extension Formatter {
    static let number: NumberFormatter = {
        let formatter = NumberFormatter()
        formatter.numberStyle = .none
        formatter.positivePrefix = "+"
        formatter.negativePrefix = "-"
        return formatter
    }()
}

func formatterFunction(number: Int) -> String {
    Formatter.number.string(for: number) ?? ""
}

struct ContentView: View {
    @State var number: Int = 450
    var body: some View { 
        Text(formatterFunction(number: number))
    }
}

If you just want to add + and - to your Text, then use simply this function below:

func formatterFunction(number: Int) -> String {
    if number > 0 {
        return "+" + String(number)
    }
    else if number < 0 {
        return "-" + String(abs(number))
    }
    else {
        return String(number)
    }
}

Swift needs to be told to cast the Int to an NSNumber for the formatter.

Text("\(450 , formatter: Self.numberFormat)")

No other changes to your code necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM