TextField 即在文本输入期间显示%
输入后如何附加%符号
extension ViewController: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let currentText = textField.text! as NSString
let newText = currentText.replacingCharacters(in: range, with: string)
if newText.hasSuffix("%"){
textField.text = newText
}else{
textField.text = "\(newText) %"
}
return true
}
}
就像图片中我只想在数字后1%的签名。
how to append % sign after input
extension ViewController: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let currentText = textField.text! as NSString
let newText = currentText.replacingCharacters(in: range, with: string)
if newText.hasSuffix("%"){
textField.text = newText
}else{
textField.text = "\(newText) %"
}
return true
}
}
as in the picture i just want 1 % sign after the numbers.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
https://developer.apple.com/documentation/uikit/uitextfielddelegate/1619599-文本字段 说:
可能是因为您返回真正的快速更新,旧文本替换了您刚刚设置的文本字段的文本属性。尝试返回 false,因为这“保留旧文本”,该文本已由您的代码更新。
https://developer.apple.com/documentation/uikit/uitextfielddelegate/1619599-textfield says:
probably because you return true swift updates with the old text replacing the text property of the text-field you just set. Try returning false as this 'keeps the old text' which is already updated by your code.
原因是在文本输入之前呼叫func syrechangecharactersin,这是错误的。我们想要的是在值更改之后,如果没有,则在最后添加%。这是这样做的代码。
The reason is func shouldChangeCharactersIn call before the text is input so it is wrong. What we want in here is after the value changed, add % at the end if not have. Here is the code for do that.