usernameField と passwordField の 2 つの UITextField があります。両方のフィールドについて、以下のコードを実装して、ユーザーが空白を入力できないようにし (スペースバーを使用)、各テキストフィールドの最大長を制限しようとしています。空白のコードは正常に機能しますが、Max Length は失敗します。
//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;
}
}
}