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