2012-02-03 58 views

回答

0

找到最好的方法來解決這個問題。工程就像一個冠軍:)

.m文件裏面

//#define CHARACTERS @" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" 

//#define CHARACTERS_NUMBERS [CHARACTERS stringByAppendingString:@"1234567890"] 
///// Inside shouldChangeCharactersInRange 

///////////>>>>>>>>>>>>>>>>>> 

if(textField== txtFldAlpha) 
    { 

     //Alpha only 

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

     NSCharacterSet *unacceptedInput = 
     [[NSCharacterSet characterSetWithCharactersInString:CHARACTERS] invertedSet]; 

     // Create array of strings from incoming string using the unacceptable 
     // characters as the trigger of where to split the string. 
     // If array has more than one entry, there was at least one unacceptable character 
     if ([[string componentsSeparatedByCharactersInSet:unacceptedInput] count] > 1) 
      return NO; 
     else 
      return YES&&(newLength < 26); 
     return YES; 
    } 

///////////<<<<<<<<<<<<<<<<<< 

///////////>>>>>>>>>>>>>>>>>> 

if(textField==txtFldNumeric) 
    { 
     //Num only 

     NSUInteger newLength = [textField.text length] + [string length] - range.length; 
     NSCharacterSet *nonNumberSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet]; 

     if ([[string componentsSeparatedByCharactersInSet:nonNumberSet] count] > 1) 
      return NO; 
     else 
      return YES&&(newLength < 6); 
     return YES; 

    } 

///////////<<<<<<<<<<<<<<<<<< 

///////////>>>>>>>>>>>>>>>>>> 

if(textField==txtFieldNumAlphaSpecial) 
    { 
     //Num,Alpha,Special field 

     NSUInteger newLength = [textField.text length] + [string length] - range.length; 
     return (newLength > 50) ? NO : YES; 
    }  
///////////<<<<<<<<<<<<<<<<<< 
3

可以形成正則表達式的字符串,並使用它。請在下面找到一個代碼示例,僅允許字母和空格。

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
{ 
    NSString *stringPlace = @"[a-z A-Z]*"; 
    NSPredicate *testPlace = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", stringPlace]; 
    BOOL matches = [testPlace evaluateWithObject:string]; 

    // if it does not match the regular expression and more than 5 characters 
    if (!matches && string.length > 5) 
    { 
     return NO; 
    } 
    return YES; 
} 
+0

+1。更快,更優雅的解決方案。 – tipycalFlow 2012-09-11 04:47:25

相關問題