iOS Swift Tutorial – Stop segue and show alert if text box is empty

iOS Swift Tutorial – Stop segue and show alert if text box is empty

iOS Simulator Screen Shot 20 Sep 2014 18.26.18
The iOS Swift journey continues! following from my last iOS Swift post where I showed you how to pass data between ViewControllers I have had a couple people ask how to validate the text box and if empty show an alert and prevent the segue from happening.

This is rather simple, I am using the same project that we set up together here so if you are not familiar with this, you may want to check that out although this code can be adapted to any project.

The function we need to override is called shouldPerformSegueWithIdentifier and here is the code we need to add in to the first ViewController (or equivalent in your project, wherever the text box is located):

override func shouldPerformSegueWithIdentifier(identifier: String!, sender: AnyObject!) -> Bool {
        if identifier == "segueTest" {
            
            if (textField.text.isEmpty) {
                
                let alert = UIAlertView()
                alert.title = "No Text"
                alert.message = "Please Enter Text In The Box"
                alert.addButtonWithTitle("Ok")
                alert.show()
                
                return false
            }
            
            else {
                return true
            }
        }
        
        // by default, transition
        return true
    }

Screen Shot 2014-09-20 at 18.15.33

Thats it! remember in Swift you have to have a default return on the function and this is a simply if statement within the shouldPerformSegueWithIdentifier function.

Let me know how you get on and if you have any questions I will try my best to answer these, remember to like and share this post if you found it to be of some use!

Happy Coding!

Menu Title