我正在格式化一个UITextField
这样它在打字时变成逗号分隔(十进制样式)。
所以12345678
变成12,345,678
现在,当我编辑 时UITextField
,说我要删除5
,当时我点击 after5
并删除它,但光标立即移动到文本的末尾,即 after 8
。
这是我在输入时用来格式化小数的代码:
func checkTextField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if ((string == "0" || string == "") && (textField.text! as NSString).range(of: ".").location < range.location) {
return true
}
let allowedCharacterSet = NSCharacterSet(charactersIn: "0123456789.").inverted
let filtered = string.components(separatedBy: allowedCharacterSet)
let component = filtered.joined(separator: "")
let isNumeric = string == component
if isNumeric {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
let numberWithOutCommas = newString.replacingOccurrences(of: ",", with: "")
let number = formatter.number(from: numberWithOutCommas)
if number != nil {
var formattedString = formatter.string(from: number!)
if string == "." && range.location == textField.text?.count {
formattedString = formattedString?.appending(".")
}
textField.text = formattedString
} else {
textField.text = nil
}
}
return false
}
它是这样调用的:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let textFieldText = (textField.text! as NSString).replacingCharacters(in: range, with: string)
let checkForCurrency = checkTextField(textField, shouldChangeCharactersIn: range, replacementString: string)
return checkForCurrency
}
我尝试了以下方法但徒劳无功:
光标移动的原因可能是什么?它应该类似于此链接中的任何帮助将不胜感激!