如何使用Swift在文本字段(从右到左)输入货币格式?

如何使用Swift在文本字段(从右到左)输入货币格式?,第1张

如何使用Swift在文本字段(从右到左)输入货币格式?

对于 Swift 3 。在文本字段上输入货币格式(从右到左)

override func viewDidLoad() {    super.viewDidLoad()    textField.addTarget(self, action: #selector(myTextFieldDidChange), for: .editingChanged)}func myTextFieldDidChange(_ textField: UITextField) {    if let amountString = textField.text?.currencyInputFormatting() {        textField.text = amountString    }}extension String {    // formatting text for currency textField    func currencyInputFormatting() -> String {        var number: NSNumber!        let formatter = NumberFormatter()        formatter.numberStyle = .currencyAccounting        formatter.currencySymbol = "$"        formatter.maximumFractionDigits = 2        formatter.minimumFractionDigits = 2        var amountWithPrefix = self        // remove from String: "$", ".", ","        let regex = try! NSRegularexpression(pattern: "[^0-9]", options: .caseInsensitive)        amountWithPrefix = regex.stringByReplacingMatches(in: amountWithPrefix, options: NSRegularexpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count), withTemplate: "")        let double = (amountWithPrefix as NSString).doublevalue        number = NSNumber(value: (double / 100))        // if first number is 0 or all numbers were deleted        guard number != 0 as NSNumber else { return ""        }        return formatter.string(from: number)!    }}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5620054.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存