强制在UITextField中输入某些字符类型 [英] Forcing entry of certain character types in UITextField

查看:41
本文介绍了强制在UITextField中输入某些字符类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个UITextField,用户正在输入一个注册号,其格式为:11-11-1111

If I have a UITextField which the user is inputing a registration number, which has the format: 11-11-1111

(即2位,破折号,2位数字,破折号,四位数字)

(that is 2 digits, a dash, 2 digits, a dash, four digits)

如何强制用户仅输入此类数据(因为他们实际上是在输入数据)...因此,他们不能在第一个字符中输入0-9以外的任何字符,而在输入字符时只能输入-"第三字符等

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.

推荐答案

从UX的角度来看,由于固定了'-'字符,因此可以通过设置 keyboardType将输入限制为仅0-9.将 UITextField 的code>属性更改为 UIKeyboardTypeNumberPad .

From a UX point of view, since the '-' characters are fixed, limit the input to just 0-9 by setting the keyboardType property of UITextField to UIKeyboardTypeNumberPad.

实施 UITextFieldDelegate 协议的 textField:shouldChangeCharactersInRange:replacementString:方法,并检查 textField.text 的长度并附加'-'字符长度为2或5时自动显示.当长度达到10个字符时,不接受任何新字符,只需删除即可.

Implement UITextFieldDelegate protocol's textField:shouldChangeCharactersInRange:replacementString: method and check the length of the textField.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.

这篇关于强制在UITextField中输入某些字符类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆