views:

30

answers:

1

i am trying to get if a uitextfield is empty, and if it is to run the follwing code in an 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];

where v.text is the text inside the uitextfield

+4  A: 

I'm assuming that your main challenge here isn't simply checking whether the text property of a UITextField is empty, but getting it to perform that check as the user types. To simply check whether the text field is empty, you'd just do:

if (aTextField.text == nil || [aTextField.text length] == 0)

However, if you're trying to get the text field to "automatically" perform the calculation whenever it becomes empty, do the following: Set a delegate for the UITextField. The delegate's textField:shouldChangeCharactersInRange:replacementString: method is called before any characters are changed in the text field. In that method, do something like:

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

You perform updateEmptyTextField after a delay because the UITextField hasn't yet applied the change that its delegate just approved. Then, in updateEmptyTextField: do something like this:

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

Note: You might need to manually run the check once when your view is first displayed, because textField:shouldChangeCharactersInRange:replacementString: won't get called until the user starts typing in the text field.

James Huddleston
great post thanks alot
Alx