Created
December 13, 2020 18:39
-
-
Save antonyalkmim/095a1c37e2a9961f50ef043a96c2e06f to your computer and use it in GitHub Desktop.
SwiftUI CurrencyTextField
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this code help to solve my problem thanks