我在这里的目标是在用户输入时格式化文本。
我不太清楚如何使用
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool { } 我已经尝试了几种方法,并且越接近我想要的是this线程的答案:
extension MyViewController: UITextFieldDelegate {
func textField(_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
if let text = textField.text,
let textRange = Range(range, in: text) {
let updatedText = text.replacingCharacters(in: textRange,
with: string)
myvalidator(text: updatedText)
}
return true
}
}我已经很接近我需要的了。我可以让控制台打印输入的文本和新文本,例如
Input: 498746454
Console:
$ 0
4$ 4
49$ 49
498$ 498
4987$ 4 987
49874$ 49 874
498746$ 498 746
4987464$ 4 987 464
49874645$ 49 874 645这就是我的第一个问题所在,因为输出比文本字段中的输入落后一个字符。
如何使它在输入文本时进行更改??
和我的第二个问题是如何让它在textfield上显示??
这是我正在使用的代码:
func myvalidator(text: String){
print(text)
}
func textField(_ textField: UITextField,shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if let text = amount.text,
let textRange = Range(range, in: text) {
let updatedText = amount.text!.replacingCharacters(in: textRange, with: "$ \((amount.text! as NSString).doubleValue.formattedWithSeparator)")
myvalidator(text: updatedText)
}
return true
}发布于 2020-05-25 05:34:31
要获得当前输入文本,在字符更改后,必须向textField添加一个自定义函数。
yourTextField.addTarget(self, action: #selector(changedCharacters(textField:)), for: .editingChanged)您的函数可以如下所示:
@objc func changedCharacters(textField: UITextField){
guard let input = textField.text else { return }
// do with your text whatever you want
}发布于 2020-05-25 05:46:56
根据您的问题,每当用户输入某个数字时,您应该知道这个数字和更新的数字应该打印在控制台中。试试下面的代码
func textField(_ textField: UITextField,shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
let updatedText = newString + "$ \(String(describing: Double(newString) ?? 0.0))"
myvalidator(text: updatedText)
return true
}将您的委托替换为上面的一个,您应该知道,每当您键入此委托时,新字符都会帮助您在textField中显示该字符。此委托字符串的最后一个参数包含最近键入的字符用户。
https://stackoverflow.com/questions/61996077
复制相似问题