Home  >  Q&A  >  body text

uitextfield - IOS textField怎样设置只能输入英文字母或者数字,不能输入汉字

RT,要弄个输入车牌后5位字符的输入框,车牌后5位只能有数字和字母,我在网上找了很多方法,都有些问题,要么就全都能输入,要么就只能输入数字,要么就到输入到5位后无法修改输入的东西,所以向大家求助,有没有什么方法可以限定输入框不能输入中文的
我现在用的这个方法
//设置键盘类型
self.textField.keyboardType = UIKeyboardTypeASCIICapable;

define kAlphaNum @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

//判断是否是数字,不是的话就输入失败
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSCharacterSet *cs;

cs = [[NSCharacterSet characterSetWithCharactersInString:kAlphaNum] invertedSet];



NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""]; //按cs分离出数组,数组按@""分离出字符串



BOOL canChange = [string isEqualToString:filtered];



return self.textField.text.length>=5?NO: canChange;

}
这个方法输入满5位后就无法删除修改了求教

大家讲道理大家讲道理2713 days ago677

reply all(3)I'll reply

  • ringa_lee

    ringa_lee2017-04-17 14:33:10

    You need to determine whether the existing content plus the content to be entered is >=5
    Add the following code and you can run it
    NSUInteger newLength = textField.text.length+string .length-range.length;
    return newLength>=5?NO : canChange;

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-17 14:33:10

    You can use macros to define an input character set string, such as:

    #define kValidChar   @”ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789″
    

    Then, determine whether the entered character can be found in the string in the relevant delegate. Not found, not accepted.

    reply
    0
  • 迷茫

    迷茫2017-04-17 14:33:10

    The inability to modify or delete after entering 5 digits is a problem with your own code. If it is greater than or equal to 5, modification will not be allowed, so naturally it will not work. What you need to check is whether the replacement complies with the specification, and whether the modified result complies with the specification. When deleting, the replacement character is empty.

    objectivecreturn self.textField.text.length>=5?NO: canChange;
    

    reply
    0
  • Cancelreply