iOS Swift – How to check if a text field is empty

iOS Swift – How to check if a text field is empty

When writing your app it may be important to validate and check if a text field is empty and then perhaps show an alert when a button is pressed for example.

This is actually a very simple thing to do but many people get stuck on things like this so I wanted to do this very quick post explaining how to do it.

In Swift we can use a boolean called isEmpty so for example if our text field is called ‘textField’ we would code this as follows:

if (textField.text.isEmpty) {
                let alert = UIAlertView()
                alert.title = "No Text"
                alert.message = "Please Enter Text In The Box"
                alert.addButtonWithTitle("Ok")
                alert.show()
}

Perhaps you want to take this a step further, in my previous post I show you how to prevent a segue if a text field is empty so be sure to check that out!

Share your thoughts below and don’t forget to share and like this post, it helps a lot!

Happy coding!

Menu Title