Search code examples
swiftuisegmentedcontrol

Segmented Control returning wrong value?


I have the following code:

@IBAction func didSelect(_ segmentIndex: Int) {
    switch segmentIndex
    {
    case 0:
        print ("1")

    case 1:
        // SHOWING THE PROFILE VIEW
        print ("2")

    default:
        print  ("break")
    }
}

I only have 2 tabs on the segment control, and whatever I click, it keeps printing "break". Why does that happen?


Solution

  • The parameter of an IBAction must be the type of the connected UI element.

    So you have to pass UISegmentedControl and switch on its selectedSegmentIndex

    @IBAction func didSelect(_ control: UISegmentedControl) {
        switch control.selectedSegmentIndex
        {
        case 0:
            print ("1")
    
        case 1:
            // SHOWING THE PROFILE VIEW
            print ("2")
    
        default:
            print  ("break")
        }
    }