Check If UITextField Contains Value

In this tutorial, you will learn how to check if a UITextField contains a value in Swift. I will cover the following topics:

  1. Understanding the isEmpty property.
  2. Using the isEmpty property to check if a UITextField is empty.
  3. Handling the case when the UITextField is empty.

If you are new to UITextField, check out this tutorial: Create UITextField Programmatically.

If you are interested in video lessons on how to write Unit tests and UI tests to test your Swift mobile app, check out this page: Unit Testing Swift Mobile App

Step 1: Understanding the isEmpty Property

In Swift, strings have a built-in property called isEmpty. This property returns true if the string has zero characters and false otherwise. Similarly, UITextField has a text property that holds the current text displayed in the text field. To check if this text is empty,  you can use the isEmpty property.

Step 2: Using the isEmpty Property to Check if a UITextField is Empty

To check if a UITextField is empty, you can use the isEmpty property in combination with optional chaining (?) and force unwrapping (!). Here’s how you can do it:

if (firstNameTextField.text?.isEmpty)! {
 // The UITextField is empty
}

In the code snippet above, (firstNameTextField.text?.isEmpty)! check if the text property of the firstNameTextField is empty. If it is, the code inside the if statement block will execute.

Step 3: Handling the Case When the UITextField is Empty

If the UITextField is empty, you might want to display an alert dialog window to inform the user that they need to enter a value. Here’s how you can do it:

if (firstNameTextField.text?.isEmpty)! {
 // The UITextField is empty
 let alert = UIAlertController(title: "Error", message: "Please enter a value.", preferredStyle: .alert)
 alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
 present(alert, animated: true, completion: nil)
}

In the code snippet above, I create an alert with a title of “Error” and a message of “Please enter a value.” Then, I add an “OK” button to the alert and present it.

Complete example

Let’s create a simple iOS app that demonstrates how to check if a UITextField contains a value using Swift. This app will contain a single UITextField and a button. When the button is tapped, the app will check if the UITextField is empty and display an alert accordingly.

import UIKit

class ViewController: UIViewController {
    // Create UITextField
    let myTextField: UITextField = UITextField(frame: CGRect(x: 0, y: 0, width: 300.00, height: 30.00))

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Position UITextField in the center of the view
        myTextField.center = self.view.center

        // Set UITextField placeholder text
        myTextField.placeholder = "Enter something..."
        myTextField.frame = CGRect(x: 0, y: self.view.bounds.height - 250, width: 200, height: 50)

        // Add UITextField as a subview
        self.view.addSubview(myTextField)

        // Create a Button
        let checkButton = UIButton(type: .system)
        checkButton.setTitle("Check", for: .normal)
        checkButton.frame = CGRect(x: 0, y: self.view.bounds.height - 100, width: 100, height: 50)
        checkButton.center.x = self.view.center.x
        checkButton.addTarget(self, action: #selector(buttonClicked), for: .touchUpInside)

        // Add Button as a subview
        self.view.addSubview(checkButton)
    }

    @objc func buttonClicked() {
        if (myTextField.text?.isEmpty)! {
            let alert = UIAlertController(title: "Error", message: "Please enter a value.", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
            present(alert, animated: true, completion: nil)
        } else {
            let alert = UIAlertController(title: "Success", message: "The UITextField contains a value.", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
            present(alert, animated: true, completion: nil)
        }
    }
}

Check If UITextField Contains Value

In this code, I override the viewDidLoad() method, which is called after the controller’s view is loaded into memory. Inside this method, I create a UITextField, configure its properties, and add it as a subview to the view controller’s view. I also create a button and add it as a subview to the view controller’s view.

The buttonClicked() method is connected to the button’s touchUpInside event. When the button is clicked, this method is called. Inside this method, I check if the UITextField is empty and display an alert accordingly.

Conclusion

That’s it! In this tutorial, you have learned how to check if a UITextField contains a value in Swift. Remember to always ensure that the required fields in your forms are filled in by the user to prevent unexpected behaviour or errors in your app.

To learn more about Swift and to find other useful code examples, please check the Swift Code Examples page.

Happy Coding!

If you are interested in video lessons on how to write Unit tests and UI tests to test your Swift mobile app, check out this page: Unit Testing Swift Mobile App

Leave a Reply

Your email address will not be published. Required fields are marked *