如何检测uitextfield长度

Ale*_*lea 1 iphone uitextfield

我试图得到一个uitextfield是空的,如果它是在ibaction中运行以下代码.

float uu = ([u.text floatValue]);
float ss = ([s.text floatValue ]);
float aa = ([a.text floatValue ]);


float x1float = sqrt((uu * uu) +(2*aa*ss));


v.text = [[NSString alloc]initWithFormat:@"%f", x1float];
Run Code Online (Sandbox Code Playgroud)

其中v.text是uitextfield中的文本

Jam*_*ton 5

我假设你的主要挑战不仅仅是检查texta 的属性是否UITextField为空,而是让它在用户输入时执行该检查.要简单地检查文本字段是否为空,您只需执行以下操作:

if (aTextField.text == nil || [aTextField.text length] == 0)
Run Code Online (Sandbox Code Playgroud)

但是,如果您尝试使文本字段"自动"执行计算,只要它变为空,请执行以下操作:为UITextField.设置委托.textField:shouldChangeCharactersInRange:replacementString:在文本字段中更改任何字符之前调用委托的方法.在该方法中,执行以下操作:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    [self performSelector:@selector(updateEmptyTextField:) withObject:textField afterDelay:0];
    return YES;
}
Run Code Online (Sandbox Code Playgroud)

updateEmptyTextField延迟后执行,因为UITextField尚未应用其代表刚刚批准的更改.然后,updateEmptyTextField:做这样的事情:

- (void)updateEmptyTextField:(UITextField *)aTextField {
    if (aTextField.text == nil || [aTextField.text length] == 0) {
        // Replace empty text in aTextField
    }
}
Run Code Online (Sandbox Code Playgroud)

注意:您可能需要在首次显示视图时手动运行一次检查,因为textField:shouldChangeCharactersInRange:replacementString:在用户开始键入文本字段之前不会调用.