iosswiftsegmentedcontrol

How to call a function when the index for you SegmentedControl is changed


I'm trying to call a fucntion "indexChanged" when my UISegmentedControl changes index. I'm using the .addAction function that is apart of this class. I receive this warning: "No method declared with Objective-C selector 'indexChanged:'", yet even when I add a @objc tag next to the "indexChanged" function, I receive more errors.

Is there an alternative way to call a function when the SegementedControl index changes? Some code is below:

let items = ["Donors", "Cars"]
let controller = UISegmentedControl(items: items)
    controller.selectedSegmentIndex = 0

    let frame = UIScreen.main.bounds
    controller.frame = CGRect(x: frame.maxX - 135, y: frame.minY + 10,
                            width: frame.width - 250, height: frame.height*0.03)


    controller.addTarget(self, action: "indexChanged:", for: .valueChanged)
    
    
    map.addSubview(customSC) // map is a UIKit Map



func indexChanged(_ sender: UISegmentedControl) {
    if sender.selectedSegmentIndex == 0 {
        print("Select 0")
    } else if sender.selectedSegmentIndex == 1 {
        print("Select 1")
    }
}

Thanks a bunch!


Solution

  • You're very close! You didn't explain the extra errors you got, but I successfully compiled your code by changing two lines:

      controller.addTarget(self, action: "indexChanged:", for: .valueChanged)
    

    becomes:

        controller.addTarget(self, action: #selector(indexChanged(_:)) , for: .valueChanged)
    

    and

    func indexChanged(_ sender: UISegmentedControl) {
    

    needs the @objc to work:

    @objc
    func indexChanged(_ sender: UISegmentedControl) {