2013-01-16 119 views
0

我想UITextField只允許alphabets.SpecialCharacters(@,!,,,)和數量都沒有限制的鍵盤類型的allowed.So思想txtfirstname.keyboardType = UIKeyboardTypeAlphabet;鍵盤類型爲UITextField

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

但是,當我按下號碼,然後還也會有越來越文本框輸入。爲什麼這樣?

當在txtfirstname中按下數字或特殊字符時,它應該輸入到文本字段中。

我該怎麼辦?

回答

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); 


} 
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; 
      } 
}