放置范围并避免文本字段中的特殊字符

时间:2016-03-09 12:28:36

标签: ios objective-c uitextfield uitextfielddelegate

我在iOS上工作。我有一个文本字段,其范围应为7位数,并避免使用特殊字符。我只想输入0-9999999之间的数字。请帮忙

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
{    
       if(range.length + range.location > textField.text.length)
       {
          return NO;
       }

        NSUInteger newLength = [textField.text length] + [string length] - range.length;
        return newLength <= 7;

}

2 个答案:

答案 0 :(得分:2)

使用此

#define acceptableCharacterSet @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:acceptableCharacterSet] invertedSet];

    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];

    if(![string isEqualToString:filtered])
        return NO;
    NSUInteger newLength = [textField.text length] + [string length] - range.length;
    return (newLength > 7) ? NO : YES;
}

答案 1 :(得分:0)

在您的文本字段委托方法 shouldChangeCharactersInRange

这将只允许0-9个数字不允许使用字母,并且不允许使用特殊字符

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSCharacterSet *aCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
            for (int i = 0; i < [string length]; i++) {
                unichar aCharacter = [string characterAtIndex:i];
                if (![aCharacterSet characterIsMember:aCharacter]) {
                    return NO;
                }
                  return YES;
            }

}