Привет. Вот мое решение.
import UIKit
extension Numeric { // for Swift 3 use FloatingPoint or Int
func currency(locale: String, symbol: Bool = true) -> String {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.locale = Locale(identifier: locale)
if !symbol {
formatter.currencySymbol = ""
}
let result = formatter.string(for: self) ?? ""
return result
}
}
Код ViewController
var price: String!
var priceNumber: CGFloat!
@IBOutlet weak var priceInput: UITextField!
ViewDidLoad
priceInput.addTarget(self, action: #selector(priceInputChanged), for: .editingChanged)
priceInput.tintColor = .clear
priceInput.delegate = self
UITextFieldDelegate в вашем ViewController
@objc func priceInputChanged(_ textField: UITextField){
if localIdentifier != nil {
priceInput.text = priceNumber.currency(locale: localIdentifier, symbol: false)
}
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField.tag == 3 {
if string.isEmpty {
if price.count > 0 {
let last = price.removeLast()
if last == "." {
if price.count > 0 {
price.removeLast()
}
}
}
}else {
price.append(string)
}
if let input = price {
let n = NumberFormatter().number(from: input) ?? 0
priceNumber = CGFloat(truncating: n)
if localIdentifier != nil {
priceInput.text = priceNumber.currency(locale: localIdentifier, symbol: false)
}
}
}
return true
}
Вот и все