首页 > 解决方案 > Swift 数字格式器货币问题

问题描述

例如,我希望我的 textField 显示5.000,00,我设法限制我的用户可以输入的字符,但我的货币不起作用。另外我是 Swift 的新手,如何让这种货币发挥作用?

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    let formatter = NumberFormatter()
    formatter.numberStyle = .currency
    formatter.allowsFloats = true
    formatter.currencyDecimalSeparator = ","
    formatter.alwaysShowsDecimalSeparator = true
    formatter.locale = Locale(identifier: "pt_BR")
    formatter.currencyCode = "BRL"
    formatter.maximumFractionDigits = 0

    let currentText = textField.text ?? ","
    guard let stringRange = Range(range, in: currentText) else { return false}
    let updatedText = currentText.replacingCharacters(in: stringRange, with: string)

    if let groupingSeparator = formatter.groupingSeparator {

        if string == groupingSeparator {
            return true
        }


        if let textWithoutGroupingSeparator = textField.text?.replacingOccurrences(of: groupingSeparator, with: "") {
            var totalTextWithoutGroupingSeparators = textWithoutGroupingSeparator + string
            if string.isEmpty { // pressed Backspace key
                totalTextWithoutGroupingSeparators.removeLast()
            }
            if let numberWithoutGroupingSeparator = formatter.number(from: totalTextWithoutGroupingSeparators),
                let formattedText = formatter.string(from: numberWithoutGroupingSeparator) {

                textField.text = formattedText
                return false
            }
            return updatedText.count <= 8
        }
    }
    return true
}

标签: swift

解决方案


我用字符串扩展解决了这个问题,以前我在我的视图控制器上使用了一个函数,这样做为我解决了,你只需要改变你的语言环境就可以了。

扩展字符串 {

// formatting text for currency textField
func currencyInputFormatting() -> String {

    var number: NSNumber!
    let formatter = NumberFormatter()
    formatter.numberStyle = .decimal
    formatter.locale = Locale(identifier: "pt_BR")
    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.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 ""
    }
    print(formatter.string(from: number))
    return formatter.string(from: number)!
}

}


推荐阅读