4

我一直在试图找到解决方案。将UITextField格式化为价格(XXX,XXX.XX)

我只是想要一个UITextField正确格式化输入的数字作为价格。这意味着只允许使用一个小数点,在该点之后有两个数字(如果键入的话)和一个','来分隔大数字(例如150,000)。

这就是价格如何正确格式化的原因,为什么很难正确对待?

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

+0

快速的问题:你想改变它,因为用户写道,或者在击中enter/next后? – Can

+0

随着用户正在改变它(实时)。 –

回答

1

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

通过代码,这将是[myNumberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle]

谨防价格的格式非常不同,这取决于语言环境。例如在德国,点用作千位分隔符,逗号用作小数点。使用样式而不是固定格式可以为您处理这些差异。

+0

Err我在哪里可以找到要格式化的数字格式。我没有看到它?其次,它会更新的时候shouldChangeCharactersInRange发生的数量? –

+0

我没有看到你的格式化数字更新“活”的要求。在这种情况下,我的回答不会对你有所帮助,对不起。 – omz

0

嗨,这是我的解决方案。

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 
    } 

} 

视图控制器代码

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 
} 

就是这样