我一直在绞尽脑汁寻找解决方案。
我只是想要一个UITextField来正确地格式化一个输入的数字作为价格。这意味着只允许一个小数点,小数点后两个数字(如果他们是输入的)和一个',‘来分隔大数字(例如150,000)。
这就是价格正确格式化的方式,那么为什么正确的价格这么难呢?
我最接近的解决方案是this code。然而,它的问题是,在键入四位数字后,它将恢复为0??这已经接近解决方案了,我就是不明白为什么它会有这种奇怪的行为。
发布于 2011-09-09 05:32:01
你实际上不需要任何代码来做这件事。只需在nib文件中的文本字段上拖动一个数字格式化程序,并将其配置为使用"Currency“样式。
通过代码,这将是[myNumberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle]
请注意,价格的格式因地区不同而有很大差异。例如,在德国,点用作千位分隔符,逗号用作小数点。使用样式而不是固定的格式可以为您处理这些差异。
发布于 2018-02-05 21:28:51
嗨,这是我的解决方案。
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 = selfUITextFieldDelegate in Your 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
}就这样
https://stackoverflow.com/questions/7354383
复制相似问题