gpt4 book ai didi

ios - UITextField 显示格式为不带小数点的货币

转载 作者:行者123 更新时间:2023-11-28 09:53:48 24 4
gpt4 key购买 nike

我正在尝试制作一个 UITextField,即使用户正在编辑,输入内容也会以货币格式永久显示。它应该像这样工作:

$0

用户类型 1

$1

用户类型 2

$12

用户类型 0

$120

用户类型 0

$1,200

用户类型 0

$12,000

我设法使用 NumberFormatter 获得最终格式

textField.text = (numberFormatter.string(from: NSNumber(value: Int(textField.text!)!)))?.components(separatedBy: ".")[0]

但是一旦我在 textField 中格式化文本,后续输入将导致错误,如:

$1,000

用户类型 0

$1,0000 //number formatter cannot recognise this as a format of currency

无论如何,我是否可以操纵输入以允许用户只需要键入数字,但该值以带有符号加逗号的正确货币格式显示 - 例如 1,200,000 美元。无论数字的数量如何 - 但逻辑上最多 10 位就足够了。

我当前的 textField shouldChangeCharactersInRange 是这样的:

    textField.text = numberFormatter.number(from: textField.text!)?.description

if(range.length == 1){ //Backspace
if(textField.text?.characters.count == 1){
textField.text = "$0"
return false
}
return true
}
if(string.trimmingCharacters(in: CharacterSet.decimalDigits.inverted) == ""){
textField.text = (numberFormatter.string(from: NSNumber(value: Int(textField.text!)!)))?.components(separatedBy: ".")[0]
return false
}
if(string == ".") {
textField.text = (numberFormatter.string(from: NSNumber(value: Int(textField.text!)!)))?.components(separatedBy: ".")[0]
return false
}

textField.text = (numberFormatter.string(from: NSNumber(value: Int(textField.text!.append(string)!)!)))?.components(separatedBy: ".")[0]
return false

最佳答案

试试下面的代码

extension ViewController: UITextFieldDelegate {

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

let text: NSString = (textField.text ?? "") as NSString
let finalString = text.replacingCharacters(in: range, with: string)

// 'currency' is a String extension that doews all the number styling
amountTextField.text = finalString.currency

// returning 'false' so that textfield will not be updated here, instead from styling extension
return false
}
}

extension String {
var currency: String {
// removing all characters from string before formatting
let stringWithoutSymbol = self.replacingOccurrences(of: "$", with: "")
let stringWithoutComma = stringWithoutSymbol.replacingOccurrences(of: ",", with: "")

let styler = NumberFormatter()
styler.minimumFractionDigits = 0
styler.maximumFractionDigits = 0
styler.currencySymbol = "$"
styler.numberStyle = .currency

if let result = NumberFormatter().number(from: stringWithoutComma) {
return styler.string(from: result)!
}

return self
}
}

关于ios - UITextField 显示格式为不带小数点的货币,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41255948/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com