I have a question regarding this answer: https://stackoverflow.com/a/29783546/2529173
It works great, but in my app I need the user to select/change his currency. I've tried to set this with a locale like this:
class CurrencyField: UITextField {
override func awakeFromNib() {
super.awakeFromNib()
addTarget(self, action: #selector(editingChanged), for: .editingChanged)
keyboardType = .numberPad
textAlignment = .right
editingChanged()
}
func editingChanged() {
Formatter.currency.locale = Locale(identifier: "es_CL")
text = Formatter.currency.string(from: (Double(string.numbers.integer) / 100) as NSNumber)
}
}
struct Formatter {
static let currency = NumberFormatter(numberStyle: .currency)
}
extension UITextField {
var string: String { return text ?? "" }
}
extension String {
var numbers: String { return components(separatedBy: Numbers.characterSet.inverted).joined() }
var integer: Int { return Int(numbers) ?? 0 }
}
struct Numbers { static let characterSet = CharacterSet(charactersIn: "0123456789") }
extension NumberFormatter {
convenience init(numberStyle: NumberFormatter.Style) {
self.init()
self.numberStyle = numberStyle
}
}
I it's because the NumberFormatter doesn't output decimals for this currency. Is there a way to get this work?