我正在尝试验证 textField 中的文本长度。这是我的尝试
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *textLenght = [NSString stringWithFormat:@"%@", [textField text]];
if ([textLenght length] > 5)
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Message"
message:@"Too long"
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil, nil];
[alert show];
[alert release];
return NO;
}
return YES;
}
这段代码运行良好。当我键入超过 5 个字符时,会显示警告框。问题是当我尝试删除文本字段的最后一个字符时,警告框再次显示。
如何解决?
最佳答案
你必须先创建实际的字符串
NSString *str = [textField.text stringByReplacingCharactersInRange:range withString:text];
你之后检查长度
int length = str.length;
然后继续进行 if(长度)检查。
这种方式首先创建所需的字符串(同时考虑退格)。
关于objective-c - 验证文本字段长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9620542/