0

我想要一个UITextField只允许alphabets.SpecialCharacters(@,!,,,)并且不允许数字。所以想到将键盘类型限制为txtfirstname.keyboardType = UIKeyboardTypeAlphabet;

-(void)viewDidLoad{
 txtfirstname.keyboardType = UIKeyboardTypeAlphabet;
}

但是当我按下数字时,它们也会被输入到文本字段中。为什么会这样?

当按下数字或特殊字符时,txtfirstname它应该被输入到文本字段中。

我该怎么做?

4

2 回答 2

1

这里使用下面的函数...提一下你需要什么 NSCharacterSet 中的字符..

-(NSString *) formatIdentificationNumber:(NSString *)string
{
    NSCharacterSet * invalidNumberSet = [NSCharacterSet characterSetWithCharactersInString:@"àáâäæãåçćčèéêëęėîïìíįłñńôöòóõœøßśšûüùúŵŷÿźžż°§¿’‘€$£¥₩\n1234567890"];
    NSString  * result  = @"";
    NSScanner * scanner = [NSScanner scannerWithString:string];
    NSString  * scannerResult;

    [scanner setCharactersToBeSkipped:nil];

    while (![scanner isAtEnd])
    {
        if([scanner scanUpToCharactersFromSet:invalidNumberSet intoString:&scannerResult])
        {
            result = [result stringByAppendingString:scannerResult];
        }else
        {
            if(![scanner isAtEnd])
            {
                [scanner setScanLocation:[scanner scanLocation]+1];
            }
        }
    }

    return result;
} 

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{

    if(![string isEqualToString:@""])
    {
        if(textField == textfieldname)
        {
            if ([[self formatIdentificationNumber:string] isEqualToString:@""] && ![string isEqualToString:@""]) {
                return NO;
            }   
}
于 2013-01-16T11:44:31.780 回答
0

尝试这个

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
 {
     static NSCharacterSet *charSet2 = nil;
     if(!charSet2) 
  {

     charSet2 = [[NSCharacterSet  characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ./,':+_)\(*~`=&^%$#@!,-?<>\"{}][| "] invertedSet];

  } 
        NSRange location = [string rangeOfCharacterFromSet:charSet2];
        return (location.location == NSNotFound);


 }
于 2013-01-16T11:43:55.480 回答