Conditional Segue Using Storyboard
For conditional segues, don't start a segue from a button as you normally do.
Instead of that use the following steps:
In your storyboad, start a segue directly from the source view controller to the destination view controller. For doing this, you can drag your source view controller's icon on the bar just below the view to the destination view controller on the main canvas area. Just remember you have to connect two view controllers directly and not with any control.
Enter a suitable segue identifier for this segue. For example say "conditionSegue"
Now, in your source view controller’s .m file perform your condition and call
-performSegueWithIdentifier:sender:
method on "self" like this:-(void)loadDestinationVC{
if(condition == YES){
[self performSegueWithIdentifier:@"conditionSegue" sender:nil];
}
}
I hope I made it clear.
How to perform conditional segue operation in swift?
change
performSegue(withIdentifier: "toMessageRoom", sender: self)
to
performSegue(withIdentifier: "toMessageRoom", sender: sender)
How to perform conditional segue
You have created segue from the UIButton
to a viewController
that is the reason segue happens before the execution of condition. Instead of that remove that segue from storyboard and create another from your ViewController
to DestinationViewController
.
Conditional Segue in Swift
You can do the credentials check in the following method in your ViewController
:
func shouldPerformSegueWithIdentifier(_ identifier: String!,
sender: AnyObject!) -> Bool
In alternative, you can bind the UIButton
to an action in your view controller, perform the checks here and then trigger a segue by code.
How to perform a segue only if a condition is true
Your reasoning is correct. Check the following points to make sure your code is working:
- You have a segue from your button to your destination view controller.
- Your segue identifier is segue1 as in your code.
- Your
isEmpty
works when theUITextField
is empty.
If those are correct you need to override shouldPerformSegue(withIdentifier:sender:)
as you did but you can improve the code and add the alert by doing the following:
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
if identifier == "segue1" {
if txtField.text?.isEmpty {
let alertController = UIAlertController(
title: "Alert",
message: "Input value",
preferredStyle: .alert
)
present(alertController, animated: true, completion: nil)
return false
}
}
return true
}
For more information about how to use UIAlertController
check the Documentation
Is there a way to perform a conditional segue in a swift ViewController?
I have solved this issue.
The code above is actually correct and functional. The issue was that the handleSignIn method was called within:
@IBAction func didTapLogin(_ sender: Any) {...}
That button itself was the segue connection with the identifier "toHome," and so regardless of what the if/else block evaluated to, the application proceeded to the home menu.
Once I deleted and reestablished the segue "toHome" from the LoginViewController to the HomeViewController (not the Log In button to the HomeViewController), this code worked properly.
How to perform different segue based on condition from a button click in swift?
I think, You are trying to connect the button to perform segue with multiple ViewController Right?? which is not possible
Instead that you have to connect segue between View Controllers
Adding a segue between two viewControllers:
From the Interface Builder, ctrl + drag between the two viewControllers that you want to link. You should see:
And now based on you condition you should perform segue with identifiers like below:
@IBAction func NextViewController(_ sender: UIButton) {
if launchedBefore {
/*Use the Identifier you given in story Board*/
self.performSegue(withIdentifier: "otherVC", sender: self)
} else {
/*Use the Identifier you given in story Board*/
self.performSegue(withIdentifier: "register", sender: self))
UserDefaults.standard.set(true, forKey: "launchedBefore")
}
}
For more Descriptive answer about segue see the answer How to connect two view controllers to one button in storyboard?
How can I make a segue not occur if a condition isn't met?
What you want to do is implement something like:
override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool {
if identifier == "WhateverYourSegueIsNamed" { // you define it in the storyboard (click on the segue, then Attributes' inspector > Identifier
if textFieldRandomWord.text.isEmpty == true {
print("*** NOPE, segue wont occur")
return false
}
else {
print("*** YEP, segue will occur")
}
}
// by default, transition
return true
}
and I'm basing my answer on the great example can be seen in this related question's answer
iOS: Is there a way to use conditional segue depending on which table view cell clicked
in your didSelectItemAtIndexPath
call different segue identifier
if indexPath.row == 0 {
performSegueWithIdentifier("showPage1", sender: indexPath.row)
}
else if indexPath.row == 1 {
performSegueWithIdentifier("showPage2", sender: indexPath.row)
}
Then in your prepareForSegue
, check the condition.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showPage1" {
// do something for page 1
}
else if segue.identifier == "showPage2" {
// do something for page 2
}
}
Your segue should drag from image below to destination controller
Set condition on a segue function swift
Try to read the code and comments.
First of all, the method func prepare(for segue: UIStoryboardSegue, sender: Any?)
must not be in another method. Somehow you managed to squeeze it in func stateCondition(state: Bool)
. Second you are not calling performSegue(withIdentifier: identifier, sender: self)
anywhere. You probably should :) Check out the code, hope it helps. I remember my first segue, it took me some time to understand what is going on.
class ViewController: UIViewController {
@IBOutlet private var ageTextField: UITextField!
@IBOutlet private var genderTextField: UITextField!
@IBOutlet private var bmiLabel: UILabel!
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// 3
// This method gets called and there you do your stuff with respective VCs
if segue.identifier == "info", let infoViewController = segue.destination as? InfoViewController {
// 3.1
// If the identifer is set to INFO then you go to the InfoViewController and assigne message
infoViewController.message = "Some fields are empty"
} else if segue.identifier == "popUp", let popUpViewController = segue.destination as? PopUpViewController {
// 3.2
// If the identifer is set to POPUP then you go to PopUpViewController and assign age, gender and bmi
popUpViewController.age = "33"
popUpViewController.gender = "male"
popUpViewController.bmi = "20"
} else {
print("Identifer is none of the above")
}
}
@IBAction private func buttonTapped(_ sender: Any) {
// 1.
// First you need to figure out where you want to take the user
// You do that in the method getSegueIdentifier() where you get the identifier
let identifier = getSegueIdentifier()
// 2.
// Then you performSegue with that identifer
performSegue(withIdentifier: identifier, sender: self)
}
private func getSegueIdentifier() -> String {
if ageTextField.text?.isEmpty == true && genderTextField.text?.isEmpty == true && bmiLabel.text?.isEmpty == true {
return "info"
} else {
return "popUp"
}
}
}
class InfoViewController: UIViewController {
var message = ""
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
showAlert()
}
func showAlert() {
// show alert with message
print(message)
}
}
class PopUpViewController: UIViewController {
var age = ""
var gender = ""
var bmi = ""
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
showPopUp()
}
func showPopUp() {
// show popUp with age gender and bmi
print(age, gender, bmi)
}
}
Related Topics
Swift Deleting Table View Cell When Timer Expires
Persist Accessibility Permissions Between Builds in Xcode 13
Swift Generic Protocol Function Parameters
Swift: Casting a Floatingpoint Conforming Value to Double
Calling a Child Inside 2 Levels of Nodes
Could Not Cast Value of Type Uiview to [Customview] Using Xib
How to Unpack Multiple Levels of Nested JSON in Firebase Database
Avaudioplayer.Play() Works But Avaudioplayernode.Play() Fails
iOS 13 Swiftui: App Crashes Upon Launch on Real Device
Generic Class with Class-Bound Constraint Cannot Be Parametrized by Class-Bound Protocol
Nsurl from String Gets Truncated, Dots on the Uivideoeditorcontroller's Video Path Swift 2 iOS 8
How to Have Either or Wherefields for Firestore Query
C++ Dylib in Swift Project - Undefined Symbols for Function Exposed in Dylib
Use Huge Numbers in Apple Swift
Swiftui How to Programatically Adjust Spacing Between Images and Text
How to Loop All Firebase Children at Once in the Same Loop
Is There Difference Between Using a Constructor and Using .Init
Check If an Int Value Is Greater or Equal to Another Int? Value