Search code examples
iosswiftsegue

How to cancel a segue in certain conditions (if/else)?


I am creating an app. In a certain view, there are several text fields in which the user inputs numbers, then presses a button, and is transported into the next view controller.

How do I make it so if a person taps the button, and one or more text fields are empty, the segue cancels?

Here is my code for that area so far:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if saveButton === sender {
        let name = nameTextField.text ?? ""

        // Set the meal to be passed to MealListTableViewController after the unwind segue.
        meal = Meal(name: name)

    }

   if calcButton === sender {

    if weightInKilos.text == "" && percentOfDehydration.text == "" && ongoingLosses.text == "" && factor.text == "" {

        let alertController = UIAlertController(title: "Fields were left empty.", message:
            "You left some fields blank! Please make sure that all fields are filled in before tapping 'Calculate'.", preferredStyle: UIAlertControllerStyle.Alert)
        alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil))

        self.presentViewController(alertController, animated: true, completion: nil)

    }

    else {
        let DestViewController: ftrViewController = segue.destinationViewController as! ftrViewController

        let weightInt: Int? = Int(weightInKilos.text!)
        let dehydrationInt: Int? = Int(percentOfDehydration.text!)
        let lossesInt: Int? = Int(ongoingLosses.text!)
        let factorInt: Int? = Int(factor.text!)

        let lrs24Int = (30 * weightInt! + 70) * factorInt! + weightInt! * dehydrationInt! * 10 + lossesInt!

        let lrsPerHourint = lrs24Int / 24

        DestViewController.lrsHr = "\(lrsPerHourint)"
        DestViewController.lrs24Hrs = "\(lrs24Int)"
    }
    }
}

Solution

  • You must check everything you need BEFORE calling the segue.

    So, the user write the answers, you check if everything is ok, IF, its ok, do the segue, else, you alert the user and ask for retype the info.

    Got it?