Alek Piasecki Alek Piasecki - 1 year ago 87
iOS Question

Display a particular viewcontroller in Xcode/swift using if else conditional statements

I want a to have a conditional if statement to be run immediately when the app is open. Basically, it will be

if x = true{
segue to viewcontroller1} else{

stay on this page


This will be in Xcode and coded in swift (obviously the syntax is wrong)... what is the appropriate way to write the syntax to segue to a particular view controller if the condition is true and stay on the one that normally is opened up to upon opening the app? Also, where do I put this? I considered the viewdidload method in the, normally, first displayed viewcontroller, but the variable needs to be checked before the view loads, such that the view changes to a different one if the condition is true and that one opens first instead?

Answer Source
  1. If you want to select the scene before presenting. You can add the following in appDelegate.swift, in application(application: UIApplication, didFinishLaunchingWithOptions):

     var sceneName = "LoginScene"
     if x {
       sceneName = "OtherScene" 
     let mainStoryBoard = UIStoryboard(name: "Main", bundle: nil)
     let ViewController = mainStoryBoard.instantiateViewControllerWithIdentifier("LoginScene") as! LoginVC
     let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
       appDelegate.window?.rootViewController = ViewController

    Make sure you name the scenes in storyboard

  2. If you ok with the first scene showing and then choosing to segue:

    if x {
      self.performSegueWithIdentifier("ToMenuSegue", sender: self)
    } else {
      self.performSegueWithIdentifier("OtherSegue", sender: self)

    Again, make sure to name the segues in storyboard

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download