Forcing entry of certain character types in UITextField

拟墨画扇 提交于 2019-12-24 23:17:12

问题


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.


回答1:


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.

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.




回答2:


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:

myTextField.delegate = self

and then try:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSCharacterSet *nonNumberSet = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789."] invertedSet];
return ([string stringByTrimmingCharactersInSet:nonNumberSet].length > 0);
}



回答3:


ok figured it out from another post

use

   if (range.length != 1){
            NSCharacterSet *nonNumberSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet]; 
            returnValue = ([string stringByTrimmingCharactersInSet:nonNumberSet].length > 0);
        }


来源:https://stackoverflow.com/questions/3005940/forcing-entry-of-certain-character-types-in-uitextfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!