Skip to content

Instantly share code, notes, and snippets.

@antonyalkmim
Created December 13, 2020 18:39
Show Gist options
  • Select an option

  • Save antonyalkmim/095a1c37e2a9961f50ef043a96c2e06f to your computer and use it in GitHub Desktop.

Select an option

Save antonyalkmim/095a1c37e2a9961f50ef043a96c2e06f to your computer and use it in GitHub Desktop.
SwiftUI CurrencyTextField
import SwiftUI
struct CurrencyTextField: View {
let title: String
@Binding var amountString: String
var body: some View {
TextField(title, text: $amountString)
.keyboardType(.numberPad)
.onChange(of: amountString, perform: { newValue in
let valueFormatted = format(string: newValue)
if amountString != valueFormatted {
amountString = valueFormatted
}
})
}
private func format(string: String) -> String {
let digits = string.components(separatedBy: CharacterSet(charactersIn: "0123456789").inverted).joined()
let value = (Double(digits) ?? 0) / 100.0
let currencyFormatter = NumberFormatter()
currencyFormatter.numberStyle = .currency
currencyFormatter.currencySymbol = (Locale.current as NSLocale).object(forKey: .currencySymbol) as? String ?? ""
let valueFormatted = currencyFormatter.string(from: NSNumber(value: value)) ?? ""
return valueFormatted
}
}
@victorkabike-ios

Copy link
Copy Markdown

this code help to solve my problem thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment