views:

409

answers:

1

I have a button that I only want enabled when a textfield is not blank. I have been trying to do this by implementing the following method, without any luck.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

Is there another delegate method that I could implement that gets fired after the text is changed? In this method is there some way to tell what key is being pressed, if it's a delete or something like that?

A: 

You can just check for string.length == 0 and range.length > 0; this denotes a deletion. However what you really want is to just do the pending modification and then check that you still have a non-empty string.

Something like this (typed in, not compiled):

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString *testString = [textField.text stringByReplacingCharactersInRange:range withString:string];

    if( testString.length )
        myButton.enabled = YES;
    else
        myButton.enabled = NO;
}
Ben Lachman
Awesome, that's exactly what I was looking for. Thanks.
John Duff
If you're going for brevity you can just do: myButton.enabled = testString.length; and lose 3 lines of code.
Ben Lachman
I'd be careful about assigning an integer to a BOOL. With one of the runtimes (and I can't remember if the iPhone is it), this'll cause the control to be enabled on odd lengths and disabled on even. Suggest myButton.enabled = testString.length > 0 instead.
Steven Fisher
Oh. And length isn't a property either, come to think of it. So it should be myButton.enabled = [testString length] > 0
Steven Fisher
Dot syntax != property. It is syntactic sugar that allows calling of accessor methods. Properties use dot syntax but are more than that (compiler generated accessors, etc.).
Ben Lachman