2013-03-13 53 views
0

我有兩個UITextFields:usernameField & passwordField。對於這兩個字段,我試圖實現下面的代碼,不允許用戶輸入任何空格(使用空格鍵),也限制每個文本字段的最大長度。白色空間的代碼工作正常,但最大長度失敗。UITextField無最大字符數限制的空格

//Addressing White space and length in the form 
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { 

NSString *resultingString = [textField.text stringByReplacingCharactersInRange: range withString: string]; 
NSCharacterSet *whitespaceSet = [NSCharacterSet whitespaceCharacterSet]; 
if ([resultingString rangeOfCharacterFromSet:whitespaceSet].location == NSNotFound)  { 
    return YES; 
} else { 
    self.title.text = @"No Spaces Allowed"; 
    self.title.textColor = [UIColor yellowColor]; 
    return NO; 
} 


if (textField == self.usernameField) 
{ 
    NSInteger MAXLENGTH = 15; 

    NSUInteger oldLength = [textField.text length]; 
    NSUInteger replacementLength = [string length]; 
    NSUInteger rangeLength = range.length; 

    NSUInteger newLength = oldLength - rangeLength + replacementLength; 

    BOOL returnKey = [string rangeOfString: @"\n"].location != NSNotFound; 

    return newLength <= MAXLENGTH || returnKey; 

if (textField == self.passwordField) 
    { 
     NSInteger MAXLENGTH = 10; 

     NSUInteger oldLength = [textField.text length]; 
     NSUInteger replacementLength = [string length]; 
     NSUInteger rangeLength = range.length; 

     NSUInteger newLength = oldLength - rangeLength + replacementLength; 

     BOOL returnKey = [string rangeOfString: @"\n"].location != NSNotFound; 
     return newLength <= MAXLENGTH || returnKey; 
    } 
} 
} 

回答

1

爲了允許最多字符和拒絕空間

實施shouldChangeCharactersInRange代表

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
{ 
    BOOL _isAllowed = YES; 

    NSString *tempString = [[textField.text stringByReplacingCharactersInRange:range withString:string] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; 


    if ([self.yourTextFeildName.text isEqualToString:tempString] || [tempString length] > 5) 
    { 
     _isAllowed = NO; 
    } 

    return _isAllowed; 
} 

對於最小字符

實施textFieldDidEndEditing代表

- (void)textFieldDidEndEditing:(UITextField *)textField 
{ 
    if ([textField.text length] < 5) 
    { 
     //text field length is less than 5. 
    } 
} 
相關問題