Swift handle action on segmented control

Swift 5

// add viewController

@IBOutlet var segmentedControl: UISegmentedControl!

override func viewDidLoad() {
    super.viewDidLoad()
    segmentedControl.addTarget(self, action: #selector(CommentsViewController.indexChanged(_:)), for: .valueChanged)
}

// using change

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

with sender, use the sender name sender when you want to access in the action:

segmentControl.addTarget(self, action: #selector(changeWebView(sender:)), for: .valueChanged)

or

addTarget(self, action: #selector(changeWebView), for: .valueChanged)

You can add the same target for multiple events.

So lets say your segmentedControlValueChanged: looks like this:

@objc func segmentedControlValueChanged(_ sender: UISegmentedControl) {
    if sender.selectedSegmentIndex == 0 {
        // value for first index selected here
    }
}

Then you can add targets for more than 1 events to call this function:

segmentedControl.addTarget(self, action: #selector(segmentedControlValueChanged(_:)), for: .valueChanged)
segmentedControl.addTarget(self, action: #selector(segmentedControlValueChanged(_:)), for: .touchUpInside)

Now your function will get called when a value was changed and when the user releases his finger.