Search code examples
iosswiftuisegmentedcontrol

Linking two (or more) UISegmented Controls


I'm trying to get the answer from my first segmented control to then automatically select the answer to the second (and more) segmented controls, if the selected answer is No.

So Question1 segmented control (Yes, No, N/A), if No is selected, then make answer to Question2 (and Q3,Q4 etc) segmented control to N/A. I can get it to work on Question1 alone, ie press No but changes to N/A on Question1, but I want it to leave Question1 as No, but then change Question2 etc to N/A.

I tried changing sender to Question2, but that doesn't work.

        @IBOutlet weak var Queston2: UISegmentedControl! //Will need to add same for Q3 etc

        @IBAction func Question1(_ sender: UISegmentedControl) {

            if sender.selectedSegmentIndex == 0 {
            //Do stuff
            }

            else if sender.selectedSegmentIndex == 1 {

                sender.selectedSegmentIndex = 2                  // Change button to 'N/A', works for this question, but i want it to change Question2, not Question1.

         @IBAction func Question2(_ sender: UISegmentedControl) { // generally repeats as Question1 above.

I've found a few similar answers, but they seem far more complicated than I think I need.


Solution

  • This is basically what you could do:

    class ArrayOfSegsViewController: UIViewController {
    
        @IBOutlet var q1SegControl: UISegmentedControl!
        @IBOutlet var q2SegControl: UISegmentedControl!
        @IBOutlet var q3SegControl: UISegmentedControl!
        @IBOutlet var q4SegControl: UISegmentedControl!
        @IBOutlet var q5SegControl: UISegmentedControl!
    
    
        @IBAction func q1SegControlChangeed(_ sender: UISegmentedControl) {
    
            if sender.selectedSegmentIndex == 0 {
                // do stuff
            } else if sender.selectedSegmentIndex == 1 {
                // set all others to "N/A"
                [q2SegControl, q3SegControl, q4SegControl, q5SegControl].forEach {
                    $0.selectedSegmentIndex = 2
                }
            } else {
                // do stuff
            }
    
        }
    
    }
    

    In the == 1 block, you create an array of the other segmented controls and loop through, saying "for each control, set the selected segment index to 2."

    Side notes: use

    lowerCaseFirstChar
    

    for variables and function names. Use

    UpperCaseFirstChar 
    

    for classes / structs / enums / etc.