Search code examples
iosobjective-cuibuttonuitextfielduitextfielddelegate

Need to enable a UIButton after user has entered minimum characters in UITextField using delegate method in iOS


I have an iOS application where I have a UITextField whose maximum character length I set using the delegate method:

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

However, I now realize that I also need to enable a UIButton *myButton that I have when the user has entered at least one character in the same UITextField. How do I implement this?

Here is my relevant code that I have at the moment in my delegate method:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSUInteger newLength = [textField.text length] + [string length] - range.length;
    return (newLength > 45) ? NO : YES;
}

Solution

  • Start out with a disabled UIButton then enable the button if the textField text length is greater than 0.

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
        NSUInteger newLength = [textField.text length] + [string length] - range.length;
    
        // Enable/disable the button depending on the length of the text
        if (newLength > 0) button.enabled = YES;
        else button.enabled = NO;
    
        return (newLength > 45) ? NO : YES;
    }