CodeRatchet CodeRatchet - 5 months ago 17x
Swift Question

check textfield has value before redirecting to another view - swift

I've been learning swift for the past 3 hours, so far so good I'm currently passing hard coded data from one view to another. The issue I'm trying to resolve is the following.

I have one text field on my view, if the user has entered data into that field then I allow them to navigate to the next page after the button has been pressed, if the textfield is empty then I display an error message, seems simple right? Well I can't figure this one out unfortunately, On the button I created a push segue method so once clicked it will go from view one to view two, now I have conditioned this function to check if the textfield is empty if so don't redirect however when I click the button I see the error message but it still redirects? this is my current code:

@IBOutlet var txtfield1: UITextField!
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

if txtfield1.text.isEmpty
nameLabel.text = "error don't redirect"

let newVC: SecondViewController = segue.destinationViewController as! SecondViewController

let passedPhrase = "redirect to new controller / view"

newVC.receivedPhrase = passedPhrase


Can anyone shed any light into why this is happening?


You code is right, but you need to override this function shouldPerformSegueWithIdentifier.

You need to use this to prevent performSegueWithIdentifier if your text is empty

override func shouldPerformSegueWithIdentifier(identifier: String?,sender: AnyObject?) -> Bool {

    if txtfield1.text.isEmpty {
        return false
    } else { return true }