Enabling and Disabling a button in Xcode depending on a condition

Hey there,
I’m a beginner to Xcode (just finished a Skillshare course), but I have some experience with python and C. 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 were correct, I still wouldn’t know where to put it in the code - under viewDidLoad, 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 (the button is still enabled) when the text field is empty.

Thanks,
Jaden

Are you actually using SwiftUI like you tagged your question because the code you provided looks more like UIKit?

This also looks like a questions which would better fit Stackoverflow, there are already a lot of questions and answers to the problem you described.
For example, here is a question how to disable/enable a button based on Textfield Input (UIKit) ios - Enable a button in Swift only if all text fields have been filled out - Stack Overflow.

2 Likes

That's my mistake, thanks for the help though!

Terms of Service

Privacy Policy

Cookie Policy