How to disable a UIButton until there is text in the UITextField

Surely you must be joking? This sounds overly simplistic doesn’t it? Well, to the people familiar with Objective-C a nd can perform this operation with both hands tied behind their back, nothing to see here. Y’all can move right on.

Disabling a UIButton can be achieved by using the property ‘enabled’. Thus to disable a button, write:

[myButton setEnabled: NO];

One method of form validation is to disable a button till some text is entered into a text field. This way there is no additional check later on to see if any of the fields are blank. Also, you have to keep in mind that if some text is entered and then deleted, the button should get disabled again.

There are a few ways in which this can be achieved. The simplest way would be to use the UITextField’s delegate method. First off disable the button using the code snipped given above.
Do declare the textField’s delegate also. You can do this using code:

[textField setDelegate: self];

or using Interface Builder (IB) but Control-clicking from your textField to File’s Owner and choosing delegate. Make sure all other connections in IB are wired appropirately as well.

The key here is the check for text entered must be made every time the value in the textField is changed. Luckily there is a built in delegate called UIControlEventEditingChanged. Thus add a target to your textField when UIControlEventEditingChanged occurs. Here’s the code:

[textFields addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];

Now just write the following code snippet for your textFieldDidChange: method.

- (void)textFieldDidChange:(UITextField *)textField {
if (textField.text.length > 0)
[myButton setEnabled: YES];
[myButton setEnabled: NO];

That’s it really. The same method can be used if you’d like to dynamically check the text entered or you’d like to display a message as the users type in the textField.

Examples: Display an error message if numeric value “0” is entered in the TextField

- (void)textFieldDidChange:(UITextField *)textField {
if([textField.text isEqualToString: @”0″]
// display alert view

That brings an end to this simple tutorial. That will be $2.99.