用于UITextField的keyboardType

时间:2013-01-16 11:36:24

标签: iphone uitextfield xcode4.5

我希望UITextField仅允许alphabets.SpecialCharacters(@,!,,,),并且不允许使用数字。因此,我们考虑将键盘类型限制为txtfirstname.keyboardType = UIKeyboardTypeAlphabet;

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

但是当我按下数字时,他们也会进入文本字段。为什么会这样?

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

我该怎么做?

2 个答案:

答案 0 :(得分: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;
            }   
}

答案 1 :(得分: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);


 }