【问题标题】:Formatting a UITextField as a price (XXX,XXX.XX)将 UITextField 格式化为价格 (XXX,XXX.XX)
【发布时间】:2011-09-08 20:56:11
【问题描述】:

我一直在努力寻找解决方案。

我只是想让 UITextField 将输入的数字正确格式化为价格。这意味着只允许一个小数点,小数点后的两位数(如果输入的话)和一个','来分隔大数字(例如150,000)。

这就是正确格式化价格的方式,那么为什么很难做到正确呢?

我最接近解决方案的是this code。然而,它的问题是在输入四位数字后它会恢复为 0?这接近解决方案,我只是不明白为什么它会出现这种奇怪的行为。

【问题讨论】:

标签: iphone uitextfield string-formatting nsnumber nsnumberformatter


【解决方案1】:

您实际上不需要任何代码。只需在 nib 文件中的文本字段上拖动一个数字格式化程序并将其配置为使用“货币”样式。

通过代码[myNumberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle]

请注意,价格格式因地区而异。例如,在德国,点用作千位分隔符,逗号用作小数点。使用样式而不是固定格式可以为您解决这些差异。

【讨论】:

  • 错误我在哪里可以找到要拖动的数字格式化程序。我没看到?其次,当 shouldChangeCharactersInRange 发生时它会更新数字吗?
  • 我没有看到您要求“实时”更新格式化数字。在这种情况下,我的回答对您没有帮助,抱歉。
【解决方案2】:

嗨,这是我的解决方案。

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

ViewController 中的 UITextFieldDelegate

@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
}

就是这样

【讨论】:

    猜你喜欢
    • 2011-12-04
    • 2010-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多