【问题标题】:numberformatter (style currency) delete is not workingnumberformatter(样式货币)删除不起作用
【发布时间】:2017-03-13 12:26:10
【问题描述】:

下面是我用来格式化数字并将其重新分配回文本字段的代码。在删除文本时我遇到了一些问题,完整的文本被删除而不是逐个字符地删除,而且我也无法重新输入文本。请指导我解决这个问题。

let currencyFormatter = NumberFormatter()
let decimalFormatter = NumberFormatter()
var currentString = ""

func formatCurrency(_ string: String) {
    let numberFromField = (NSString(string: string).doubleValue)/100
    activeField?.text = currencyFormatter.string(from: NSNumber(value: numberFromField))
}

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if finalTextCount >= maxCharactersLimit && string != ""{
        return false
    }

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

    return false
}

【问题讨论】:

    标签: ios swift uitextfield number-formatting


    【解决方案1】:

    我运行了您的代码,但没有遇到这些问题。如果您使用的是 XIB 或 Storyboard,请仔细检查是否未选中“编辑开始时清除”

    另外,我需要设置变量来完成这项工作:

    var maxCharactersLimit = 10
    

    and in textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String)

    let finalTextCount = textField.text?.characters.count != nil ? textField.text!.characters.count : 0
    

    【讨论】:

    • “编辑开始时清除”未选中,但从文本字段中删除文本时遇到问题。在删除字符之前是否需要删除货币符号和分隔符?
    • 我不需要这样做。我为货币格式化程序添加了 numberStyle = .currency 和 currencySymbol = "$",删除字符后,文本字段为 $0.00。您描述的问题似乎不在您发布的代码中,也许在其他地方。
    • 是的。如果我保留多个文本字段,则删除有问题。感谢您的时间。需要调试和修复问题。
    猜你喜欢
    • 2013-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-21
    • 1970-01-01
    • 1970-01-01
    • 2018-03-08
    相关资源
    最近更新 更多