如何将UITextField限制为一组已定义的字符并限制长度?

时间:2015-01-15 07:55:01

标签: ios xcode uitextfield uitextfielddelegate

我正在使用登录和resister视图控制器。我使用:

将用户名限制为12个字符,密码限制为16个
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range   replacementString:(NSString *)string
{

  if(textField==self.userField){

      NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
      return !([newString length] > 12);
    }

    else if(textField==self.passwordField){
        NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
        return !([newString length] > 16);

    }

    return YES;

}

这很好但我也想将它限制为一组字符来阻止不需要的符号和汉字。我想定义这个集合:

#define ACCEPTABLE_CHARACTERS @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

不知道如何将它添加到上面的方法中并使两者都正常工作。如果我只检查字符集而不是长度,代码将是:

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

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

    return [string isEqualToString:filtered];
}

虽然不确定如何组合它们。有谁可以帮助我吗?谢谢!

3 个答案:

答案 0 :(得分:1)

你可以这样做(我将其分为功能以提高可读性并且易于扩展条件)

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    return ([self checkLengthOfString:newString inField:textField] && [self checkCharacter:newString]);
}


// Check Length
- (BOOL)checkLengthOfString:(NSString *)text inField:(UITextField *)textField
{
   if(textField == self.userField)
   {
      return !([text length] > 12);
   }
   else if(textField == self.passwordField)
   {
      return !([text length] > 16);
   }
}

// Check character
- (BOOL)checkCharacter:(NSString *)text
{
    BOOL status        = YES;
    NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARACTERS] invertedSet];
    NSRange r          = [text rangeOfCharacterFromSet:s];
    if (r.location != NSNotFound)
    {
       status = NO;
    }
    return status;
}

答案 1 :(得分:0)

为什么不使用regEx来匹配这些字符?

答案 2 :(得分:0)

我知道这已经得到了解答,但我有类似的情况,我发现StackOverflow上的答案都没有处理Backspace字符。

我需要将UITextField的输入限制为特定数量的AlphaNumeric字符,但能够输入空格。

另外,使用[textField length]> kMAXNUMCHARS导致了一个问题:一旦达到最大字符数,就无法退格。

所以这是我的完整解决方案。它也不允许领先的空间。保存值时(在我的情况下为PLIST文件)

将尾随空格修剪到别处

在我的Constants.h文件中,我定义了:

#define ALLOWED_CHARECTERS @" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
extern const int kMAXUSERNAMELENGTH;

然后在Constants.m中:

const int kMAXUSERNAMELENGTH = 9;

我使用行

将我的类定义为UITextFieldDelegate
[self._txtUsername.textField  setDelegate:self];

不要忘记在类定义中声明UITextFieldDelegate协议

@interface MyClass : CCNode <UITextFieldDelegate>

最后,

    //UITextFiledDelegate Protocol method
    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

        //disallow leading spaces. must allow trailing spaces- never know if we'll add another char
        //we trim trailing spaces when we save the TextField value, in our case to  Plist file
        if (range.location == 0 && [string isEqualToString:@" "]) 
            return NO;

        //we use defined ALLOWED_CHARECTERS so we can add chars later, easily. 
        //we could use [NSCharacterSet alphanumericCharacterSet] if we don't need to allow spaces
        NSCharacterSet *allowedInput = [NSCharacterSet characterSetWithCharactersInString:ALLOWED_CHARECTERS];
        NSArray* arChar = [string componentsSeparatedByCharactersInSet:allowedInput]; //arChar.count = 1 if 'allowedInput' not in 'string'

        //disallow input if its not a backspace (replacementString paramater string equal @"" if a backspace) AND
        //(disallow input >= kMAXUSERNAMELENGTH chars, OR disallow if not in allowed allowedChar set
        if ( ![string isEqual:@""]  && (  [textField.text length] >= kMAXUSERNAMELENGTH || !([arChar count] > 1)) ) 
             return NO;

        return YES;

    }

我希望这有助于某人。