强制在 UITextField 中输入某些字符类型
如果我有一个 UITextField,用户正在输入注册号,其格式为: 11-11-1111
(即2位数字,一个破折号,2位数字,一个破折号,四位数字)
我如何强制用户仅输入这种数据(因为他们实际上正在输入它)......这样他们就可以第一个字符不能输入除 0-9 之外的任何内容,第三个字符只能输入“-”等。
If I have a UITextField which the user is inputing a registration number, which has the format:
11-11-1111
(that is 2 digits, a dash, 2 digits, a dash, four digits)
How do I force the user to enter this kind of data only (as they are actually entering it)... so they can't enter anything except 0-9 in the first character, and only '-' for the third character etc.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
从用户体验的角度来看,由于“-”字符是固定的,因此可以通过将
UITextField
的keyboardType
属性设置为UIKeyboardTypeNumberPad 将输入限制为 0-9
。实现
UITextFieldDelegate
协议的textField:shouldChangeCharactersInRange:replacementString:
方法并检查textField.text
的长度,并在长度为2或5。当长度达到10个字符时,不接受任何新字符,只删除。From a UX point of view, since the '-' characters are fixed, limit the input to just 0-9 by setting the
keyboardType
property ofUITextField
toUIKeyboardTypeNumberPad
.Implement
UITextFieldDelegate
protocol'stextField:shouldChangeCharactersInRange:replacementString:
method and check the length of thetextField.text
and append the '-' character automatically when the length is 2 or 5. When the length reaches 10 characters, do not accept any new characters, just deletes.您可以使用正则表达式检查输入并显示错误消息(如果格式错误)。请参阅此处。或者,您可以在破折号处拆分字符串并查看各个部分(例如,将它们转换为整数)(请参阅 此处)。
另一种(未经测试和理论上的)方法是:将文本字段委托设置为您的控制器:
然后尝试:
You can check the input with a regex and show an error message, if it's in the wrong format. See here. Or you can split the string at the dashes and look at the parts (convert them to integer, for example) (see here).
Another (untested and theoretical) approach would be: set the textfield delegate to your controller:
and then try:
弄清楚了
好的,从另一个帖子使用中
ok figured it out from another post
use