用戶類型我使用的改變的方法,其中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
}
http://stackoverflow.com/questions/24115141/swift-converting-string-to-int/34294660?s=1|0.1034#34294660 –