如何使用swift在类的文本字段中设置货币格式

时间:2018-02-19 07:43:16

标签: swift uitextfield currency

如何设置货币格式例如在使用swift 3.2的文本域中快速2,000,000.00?当我在文本字段中输入金额时,我在文本字段中收到此响应

  

CharacterView(_core:Swift._StringCore(_baseAddress:   可选(0x00000001c464e38a),_ countndFlags:13835058055282163718,   _owner:可选(₹75.33)),_ coreOffset:1)

我的代码是:

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


    // Construct the text that will be in the field if this change is accepted

    switch string {
    case "0","1","2","3","4","5","6","7","8","9":
        currentString += string
        formatCurrency(currentString)
    default:
        if string.characters.count == 0 && currentString.characters.count != 0 {
            currentString = String(currentString.characters.dropLast())
            formatCurrency(currentString)
        }
    }
    return false    }

func formatCurrency(_ string: String) {
    print("format \(string)")
    print(txtfieldamount.text!)
    let formatter = NumberFormatter()
    formatter.numberStyle = .currency
    //formatter.locale = findLocaleByCurrencyCode("NGN")
    let numberFromField = (NSString(string: currentString).doubleValue)/100
    let temp = formatter.string(from: NSNumber(value: numberFromField))
    self.txtfieldamount.text! = String(describing: temp!.characters.dropFirst())
    print(txtfieldamount.text!)
}

1 个答案:

答案 0 :(得分:0)

这是我使用UITextFieldUIKeyboardType.decimalPad中键入文本时将货币格式设置为

的方式
class ViewController: UIViewController, UITextFieldDelegate {

    // private let currencyFormatter = CurrencyFormatter() // Default locale/settings
    // private let currencyFormatter = CurrencyFormatter(locale: "pt_BR")  // Portuguese (Brazil) locale
    private let currencyFormatter = CurrencyFormatter(maximumFractionDigits: 2)

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let newText = (textField.text! as NSString).replacingCharacters(in: range, with: string)
        guard !newText.isEmpty, textField.keyboardType == .decimalPad else { return true }

        let separator = self.currencyFormatter.decimalSeparator!
        let components = newText.components(separatedBy: separator)

        // Stop exceeding maximumFractionDigits
        if components.count > 1 && components[1].count > self.currencyFormatter.maximumFractionDigits {
            return false
        }

        guard let cleaned = components.first?.replacingOccurrences(of: "[^0-9]", with: "", options: .regularExpression) else { return true }

        var doubleValue: Double?
        if (components.count > 1) {
            doubleValue = Double(cleaned + "." + components[1])
        }

        if let value = doubleValue ?? Double(cleaned) {
            var formatted = self.currencyFormatter.beautify(value)
            if (components.count > 1 && (components[1].isEmpty || components[1].range(of: "^0*$", options: .regularExpression) != nil)) {
                formatted += separator + components[1]
            }
            textField.text = formatted
        }

        return false
    }
}

这里是CurrencyFormatter.swift的子类NumberFormatter

class CurrencyFormatter: NumberFormatter {

    override init() {
        super.init()

        self.currencySymbol = ""
        self.minimumFractionDigits = 0
        self.numberStyle = .currency
    }

    convenience init(locale: String) {
        self.init()
        self.locale = Locale(identifier: locale)
    }

    convenience init(maximumFractionDigits: Int) {
        self.init()
        self.maximumFractionDigits = maximumFractionDigits
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func beautify(_ price: Double) -> String {
        let formatted = self.string(from: NSNumber(value: price))!

        // Fixes an extra space that is left sometimes at the end of the string
        return formatted.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
    }

}

如有任何问题,请评论或改善答案。