IPhone Objective-C only enable a button if NSTextfield is not blank

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?

13.10.2009 16:02:57

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;
        myButton.enabled = NO;
16.02.2012 19:18:29
Awesome, that's exactly what I was looking for. Thanks.
John Duff 13.10.2009 17:20:16
If you're going for brevity you can just do: myButton.enabled = testString.length; and lose 3 lines of code.
Ben Lachman 13.10.2009 17:23:58
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 13.10.2009 21:36:22
Oh. And length isn't a property either, come to think of it. So it should be myButton.enabled = [testString length] > 0
Steven Fisher 13.10.2009 21:36:58
@BenLachman, I tried what you suggested and every other letter ended up disabling the button. I agree, less code is sometimes nicer! This code does what you were suggesting: myButton.enabled = testString.length > 0;
Nick 3.12.2013 20:09:55