添加逗号数值作为的UITextField

问题描述:

用户类型我使用的改变的方法,其中this我想格式化UITextField当用户在数打字。正如我想要的数字是现场格式。我期待将1000到1000,50000到50000等等。添加逗号数值作为的UITextField

我的问题是,作为我的预期值UITextField没有更新。例如,当我在UITextField中键入50000时,结果会回到5,0000而不是50,000。这里是我的代码:

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

    //check if any numbers in the textField exist before editing 
    guard let textFieldHasText = (textField.text), !textFieldHasText.isEmpty else { 
     //early escape if nil 
     return true 
    } 

    let formatter = NumberFormatter() 
    formatter.numberStyle = NumberFormatter.Style.decimal 

    //remove any existing commas 
    let textRemovedCommma = textFieldHasText.replacingOccurrences(of: ",", with: "") 

    //update the textField with commas 
    let formattedNum = formatter.string(from: NSNumber(value: Int(textRemovedCommma)!)) 
    textField.text = formattedNum 
    return true 
} 
+0

http://stackoverflow.com/questions/24115141/swift-converting-string-to-int/34294660?s=1|0.1034#34294660 –

规则号shouldChangeCharactersIn 1 - 如果你分配一个值的文本字段的text属性,你必须返回false。返回true会通知文本字段对您已修改的文本进行原始更改。这不是你想要的。

你的代码中还有一个其他的重大缺陷。它不适用于使用其他方式格式化大数字的语言环境。并非所有语言环境都使用逗号作为组分隔符。

+0

谢谢 - 我不知道我用的是真实的/错误返回错误。并感谢赶上现场问题。我会尽力解决这个问题,我会报告回来! – Sami

尝试使用NSNumberFormatter

var currencyFormatter = NumberFormatter() 
currencyFormatter.usesGroupingSeparator = true 
currencyFormatter.numberStyle = .currency 
// localize to your grouping and decimal separator 
currencyFormatter.locale = NSLocale.current 
var priceString = currencyFormatter.string(from: 9999.99) 

这将打印像= 值 “$ 9,999.99”

您还可以设置语言环境根据自己的需要。

let formatter = NumberFormatter() 
formatter.numberStyle = NumberFormatter.Style.decimal 
let textRemovedCommma = textField.text?.replacingOccurrences(of: ",", with: "") 
let formattedNum = formatter.string(from: NSNumber(value: Int(textRemovedCommma!)!)) 
textField.text = formattedNum 
+0

嘿!尽管此代码片段可能是解决方案,但[包括解释](// meta.stackexchange.com/questions/114762/explaining-entirely-基于代码的答案)确实有助于提高帖子的质量。请记住,您将来会为读者回答问题,而这些人可能不知道您的代码建议的原因。 – wing