-1

I want my textField to show 5.000,00 for instance, I manage to limit the characters that my user can type, but my currency isn't working. Also I am new to Swift, how do I get this currency to work out?

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
}
bad_coder
  • 11,289
  • 20
  • 44
  • 72
user11232391
  • 1
  • 1
  • 5
  • “but my currency isn't working” What does that mean? – matt Dec 15 '19 at 14:27
  • I mean I want this number 500000 to appear that way 5.000,00 at the textField, at this moment is appearing that way 50000000, which means it is not properly formated. – user11232391 Dec 15 '19 at 16:17
  • https://stackoverflow.com/a/29783546/2303865 You can use the custom currency field, you just need to set the locale fixed to `"pt_BR" ` – Leo Dabus Dec 15 '19 at 17:32
  • thanks guys problem solved, I just set currency rigth "pt_BR". – user11232391 Jan 03 '20 at 19:22

1 Answers1

0

I solve this with a string extension, previously I was using a function on my view controller, doing that way solve for me, you just have to change your locale and will works.

extension String {

// 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)!
}

}

user11232391
  • 1
  • 1
  • 5