检查字符串是否包含字母并取消它们
我有一个 UITextField,我只需要允许在此字段中输入数字、逗号或点。
如何检查该字符串是否包含任何字符而不是上面的字符以及如何替换/删除它们?
我的字段将存储成本,而我只需要数字、逗号或点...
任何人都可以帮助我吗?
谢谢!
I've got an UITextField and I need to allow only numbers, comma or point typing in this field.
How can I check if this string contains any character instead of these above and how can I replace/delete them?
My field will store a cost and I need only numbers, comma or point...
Can anyone help me?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
对于文本字段,您可以使用
UITextFieldDelegate
并实现textField:shouldChangeCharactersInRange:replacementString:
方法。根据文档,“每当用户在文本字段中键入新字符或删除现有字符时,文本字段都会调用此方法。”在该方法中,您应该检查所有非数字字符并将其删除。For the textfield, you could use the
UITextFieldDelegate
and implement thetextField:shouldChangeCharactersInRange:replacementString:
method. According to the docs, "the text field calls this method whenever the user types a new character in the text field or deletes an existing character." In the method, you should do a check for all non-number characters and remove them.您可以使用
UITextFieldDelegate
协议中的-textFieldDidEndEditing:
方法。每当文本字段放弃第一响应者状态(即结束编辑)时,就会调用此方法。这是检查输入字符串的机会。如果您想在输入每个字符后执行检查,请按照 donkim 的建议使用-textField:shouldChangeCharactersInRange:replacementString:
。You can use the
-textFieldDidEndEditing:
method from theUITextFieldDelegate
protocol. This method is called whenever a text field resigns the first responder status (i.e. ends editing). This is the chance to check the entered String. If you want to perform a check after each character that has been input, use-textField:shouldChangeCharactersInRange:replacementString:
as donkim suggests.相反,要检查字符串,为什么不能将文本字段的键盘值指定为 NumberPad。这样用户将无法键入字符串。
Instead to check the string why cant you assign the keyboard value of the textfield as NumberPad. So that the user will not be able to type a string.
您可以通过监视字段中的用户输入并自动删除不匹配的字符来实现此目的。创建一个 IBAction 方法:
然后将其附加到文本字段的 Editing Changed 事件。每次字段中的文本发生更改时,无论是用户键入还是用户粘贴文本,都会调用该方法。
在该方法中,您可以检查文本并删除有问题的字符,或者更礼貌地更新 UILabel 来告诉用户输入了无效字符并禁用任何提交按钮,直到问题得到修复。
You can do it by monitoring user input in the field and automatically removing non-matching characters. Create an IBAction method:
then attach it to the text field's Editing Changed event. The method will be called every time the text in the field changes, whether from the user typing or from the user pasting text in.
Inside the method you can examine the text and remove offending characters or, more politely, update a UILabel that tells the user they've entered invalid characters and disable any submit buttons until it's fixed.