Search code examples
iosswiftuisegmentedcontrol

Different ViewController if different selectedSegmentIndex


My code is

@IBAction func pressedButton(_ sender: Any) {  
        self.resignFirstResponder()
        if mySegment.selectedSegmentIndex == 0 {

Here I need if I selected Segment #0 on ViewControllerA (and press my button) then go to ViewControllerB, if Segment #1 then ViewControllerC, if Segment #2 then ViewControllerD.
Is it possible?


Solution

    1. First wire a segue for each viewController. control-drag from the viewController icon at the top of ViewControllerA to another ViewController and select the segue type.

      wiring the segue

    2. Click on the segue arrow between the viewControllers, and set its identifier in the Attributes Inspector on the right.

    3. Repeat steps 1 and 2 for each ViewControllerB, ViewControllerC and ViewControllerD giving their segues unique id's such as "segueToB", "segueToC" and "segueToD".
    4. In your button code, do the following:

      let idx = mySegment.selectedSegmentIndex
      let segueID = ["segueToB", "segueToC", "segueToD"][idx]
      self.performSegue(withIdentifier: segueID, sender: self)
      

    Demo of connecting two segues:

    wiring two segues