Search code examples
iosswiftuitableviewuisegmentedcontrol

Swift - How to get selected segment of control embedded in a UITableView cell?


I have a UITableView in a UIViewController. There are two custom cells. One of these has a UISegmentedControl.

enter image description here

So far, so good.

When I tap the control, the segmented control value changes and IBAction function runs as expected.

The problem is that the selected index always shows as -1, (aka nothing selected).

What am I missing here?

Here is the code for the value change:

 @IBAction func recurranceChanged(sender: UISegmentedControl?) {

        print ("index: ", recurrenceControl.selectedSegmentIndex) << This returns -1

        if recurrenceControl.selectedSegmentIndex == 0 {
            print("No ")
        }

        if recurrenceControl.selectedSegmentIndex == 1 {
            print("Sometimes ")

        }


        if recurrenceControl.selectedSegmentIndex == 2 {
            print("Yes")

        }

    }

Solution

  • Try this: (Also removed the '?' from UISegmentedControl as it isn't needed.)

    @IBAction func recurranceChanged(sender: UISegmentedControl) {
    
        print ("index: ", sender.selectedSegmentIndex)
    
        if sender.selectedSegmentIndex == 0 {
            print("No ")
        }
    
        if sender.selectedSegmentIndex == 1 {
            print("Sometimes ")
    
        }
    
    
        if sender.selectedSegmentIndex == 2 {
            print("Yes")
    
        }
    
    }
    

    this should solve the problem ;)