Enabling and Disabling buttons in Xcode depending on a condition

Hey there,
I’m a beginner to Xcode (just finished a CWC Skillshare course), but I have some experience with python. I’m trying to build a simple app with a text field, a text view, and a button. How it works: a number is entered into the text field, the button is pressed, some calculations happen to the number, and the result is printed to the text view. It works perfectly fine, but I would like to be able to disable the button if the text field is empty, or if the value entered into the text field is not a number.

I’ve tried:

‘’’
if (textField.text == nil) {
button.isEnabled = false
}
‘’’

and

‘’’
if (textField.text != Float) {
button.isEnabled = false
}
‘’’

(With my limited knowledge) this seems ok, but even if it was correct, I still wouldn’t know where to put in the code - under viewDidLoad, or in the IBAction of the button, or the IBOutlet of the text field? idk

The error message I receive is simply associated with trying to do math with an empty value (pressing the button when the text field is empty), but the real problem is that I’m even able to press the button at all when the text field is empty.

Thanks,
Jaden

Hi Jaden,

This is not the proper way to do this. You’re trying to compare a string ( the text of your textField) to a data type (float)

This doesn’t work, you should compare == “” which is an empty string, not compare to nil.

For checking if it is or isn’t a number you should attempt to parse the value to a float. You should do this on the onEdit function of your text field.
(Which is called each time a character is entered in the textField)

Here’s a video of how that works

Each time the user enters something in the textField you can try to parse the text and if it works or not, change your button isEnabled

1 Like

Even better is to use textField.text.isEmpty

2 Likes

Thanks so much for the help!