objective-c - 验证文本字段长度

标签 objective-c ios uitextfield uialertview

我正在尝试验证 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/

相关文章:

ios - 如何映射自定义 NSManagedObject 类中的关系

ios - 如何将选择器方法设置为 Objective-C 中文本更改的文本字段?

objective-c - 如何将选定的 TableView 值发送回不同的 View ?

ios - 将 NSData 与字节序列进行比较?

iphone - 为什么我的 Application Delegate 中的类变量没有被实例化?

ios - 关闭 Cupertino 对话 Action Flutter

ios - 在文本字段点击时显示日期选择器

ios - 如何为设置包 (Root.plist) 的 TextField 提供占位符

iphone - 如何判断 UIView 是否可见并显示在屏幕上?

iphone - 比较两个图像是否相同(iOS)