我对此答案有疑问:https://stackoverflow.com/a/29783546/2529173
效果很好,但在我的应用中,我需要用户选择/更改其货币。我尝试使用这样的语言环境来设置它:
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
}
}
我是因为NumberFormatter没有输出这种货币的小数。有没有办法让这项工作?
答案 0 :(得分:0)
这是我现在的解决方案:
class CurrencyField: UITextField {
let locale:Locale = Locale.current
override func awakeFromNib() {
super.awakeFromNib()
addTarget(self, action: #selector(editingChanged), for: .editingChanged)
keyboardType = .numberPad
textAlignment = .right
editingChanged()
}
func editingChanged() {
Formatter.currency.locale = locale
let divider:Double = pow(Double(10), Double(Formatter.currency.maximumFractionDigits))
text = Formatter.currency.string(from: (Double(string.numbers.integer) / divider) as NSNumber)
}
}