如何禁用 UITextField 中的字母字符?
在我的应用程序中,我需要允许用户仅输入数字。 我如何允许 UITextField 仅接收来自用户的数字?
In my application i need to allow users input only numbers.
How can i allow UITextField to receive only numbers from user?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
本示例中的字符是允许的,因此如果您不希望用户使用某个字符,请将其从
myCharSet
中排除。The characters in this examples are allowed, so if you dont want the user to use a character, exclude it from
myCharSet
.我更喜欢以下解决方案,它实际上可以防止除数字和退格键之外的任何输入。出于某种原因,退格键由空字符串表示,除非空字符串返回 YES,否则无法使用。当用户输入数字以外的字符时,我还会弹出一个警报视图。
I prefer the following solution that actually prevents any any input except from numbers and backspace. Backspace for some reason is represented by an empty string and could not be used unless empty string returns YES. I also popup an alert view when the user enters a character other that numbers.
这可能是最干净、最简单的解决方案,只允许正数或负数。这也允许退格。
This is perhaps the cleanest, simplest solution to allow only positive or negative numbers. This also allows backspace.
您可以做的一件事是显示数字键盘,并在文本字段旁边或其他地方添加一个动态按钮来隐藏键盘。
One thing you can do is to show the numbers key pad and beside text field or some where else add a dynamic button to hide the keyboard.
你们可能会发火..但这对我有用..只有数字(包括负数)和退格键。
you guys might flame.. but this worked for me.. only numbers (including negatives), and backspace.
这是我的解决方案,使用方法
isSupersetOfSet:
应用集合代数,这也不允许粘贴带有无效字符的文本:注意:根据 Apple 开发者库,最好缓存静态
NSCharacterSet
而不是一次又一次地创建它(这里是_numericCharSet
)。不过,我更喜欢让用户输入任何字符并验证当 textField 尝试退出第一响应者时调用的方法
textFieldShouldEndEditing:
中的值。通过这种方式,用户可以粘贴任何文本(可能由字母和数字混合组成)并将其整理到我的文本字段中。用户不喜欢看到他们的行动受到限制。
Here is my solution applying algebra of sets with the method
isSupersetOfSet:
This also doesn't allow pasting text with invalid characters:Note: according to Apple Developer Library, It's preferable cache the static
NSCharacterSet
than to create it again and again (here_numericCharSet
).However I prefer to let the user to input any character and validate the value in the method
textFieldShouldEndEditing:
called when the textField tries to resign first responder.In this manner the user can paste any text (maybe composed with a mix of letters and numbers) and tidy up it in my textFields. The users do not like to see limited their actions.
在斯威夫特
In Swift
这是一个快速示例,
不要忘记将
UITextFieldDelegate
添加到您的UIViewController
中。Here is a swift example
Don't forget to add
UITextFieldDelegate
to yourUIViewController
as well.这个线程有点旧,但为了参考,我将在 swift 3 中留下一个解决方案。该解决方案将结合
decimalDigits
和实际的小数。您可以将任何您想要的组合放在一起,但对于我的情况来说,这就是要求。This thread is a little old, but for the sake of reference I am going to leave a solution in swift 3. This solution will combine
decimalDigits
and the actual decimal. You can put together whatever combination you'd like, but for my case this is what the requirements were.