检查字符串是否包含字母并取消它们

发布于 2024-10-07 03:56:44 字数 153 浏览 0 评论 0原文


我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

望笑 2024-10-14 03:56:44

对于文本字段,您可以使用 UITextFieldDelegate 并实现 textField:shouldChangeCharactersInRange:replacementString: 方法。根据文档,“每当用户在文本字段中键入新字符或删除现有字符时,文本字段都会调用此方法。”在该方法中,您应该检查所有非数字字符并将其删除。

For the textfield, you could use the UITextFieldDelegate and implement the textField: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.

不爱素颜 2024-10-14 03:56:44

您可以使用 UITextFieldDelegate 协议中的 -textFieldDidEndEditing: 方法。每当文本字段放弃第一响应者状态(即结束编辑)时,就会调用此方法。这是检查输入字符串的机会。如果您想在输入每个字符后执行检查,请按照 donkim 的建议使用 -textField:shouldChangeCharactersInRange:replacementString:

You can use the -textFieldDidEndEditing: method from the UITextFieldDelegate 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.

季末如歌 2024-10-14 03:56:44

相反,要检查字符串,为什么不能将文本字段的键盘值指定为 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.

笑叹一世浮沉 2024-10-14 03:56:44

您可以通过监视字段中的用户输入并自动删除不匹配的字符来实现此目的。创建一个 IBAction 方法:

- (IBAction)validateEntry:(id)sender;

然后将其附加到文本字段的 Editing Changed 事件。每次字段中的文本发生更改时,无论是用户键入还是用户粘贴文本,都会调用该方法。

在该方法中,您可以检查文本并删除有问题的字符,或者更礼貌地更新 UILabel 来告诉用户输入了无效字符并禁用任何提交按钮,直到问题得到修复。

You can do it by monitoring user input in the field and automatically removing non-matching characters. Create an IBAction method:

- (IBAction)validateEntry:(id)sender;

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文