This code just format as currency on the fly a number while the user types (Brazilian format)
But I was not able to center the text in it.
What am I doing wrong?
import SwiftUI
struct Testes: View {
@State var myText: String = ""
var body: some View {
HStack{
CurrencyField(text: $myText, placeholder: "Valor")
}
}
}
struct CurrencyField: View {
@Binding var text: String
var placeholder: String
var body: some View {
HStack{
TextField(placeholder, text: $text)
.onChange(of: text, perform: { oldValue in
text = formatCurrency(textoValor: oldValue)
})
.keyboardType(.decimalPad)
.frame(width: 200, height: 40, alignment: .center)
}
.border(Color.black, width: 1)
}
func formatCurrency(textoValor: String) -> String {
let numbers = textoValor.replacingOccurrences(of: "[^0-9]", with: "", options: .regularExpression)
let n2 = Double(numbers) ?? 0
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.decimalSeparator = ","
formatter.groupingSeparator = "."
formatter.minimumFractionDigits = 2
formatter.maximumFractionDigits = 2
formatter.minimumIntegerDigits = 1
formatter.locale = Locale(identifier: "pt_BR")
return formatter.string(from: NSNumber(value: n2 / 100)) ?? "$0"
}
}