Search code examples
iosswiftuibuttonuisegmentedcontrol

Calling button actions in segmented control


I have a segmented control action method with two segments

@IBAction func segmentChanged(_ sender: UISegmentedControl) { 

    // What goes here for displaying data similar to buttonsTapped? 
}

I have three buttons as follows

 @IBOutlet weak var buttonOne: UIButton!
 @IBOutlet weak var buttonTwo: UIButton!
 @IBOutlet weak var buttonThree: UIButton!

I have an action method for all 3 buttons,

 @IBAction func buttonsTapped(_ sender: UIButton) { 

    switch sender {
    case buttonOne:
     print("Button one Tapped")
    case buttonTwo:
     print("Button two tapped")
    case buttonThree:
     print("Button three tapped")
    default: break
    }

  if segmentedControl.selectedSegmentIndex == 0
        {
            print("First Segment")
        }
        else
        {
            print("Second Segment")
        }
  }

When I tap on buttonOne, I am getting "First Segment" and "Button One Tapped" as it is in the first segment. Similarly, buttonTwo and buttonThree, are displaying correct messages on the console.

But when I am changing the segmented control, I am not getting any messages on the console. I tried by calling buttonOne.sendActions(for: .touchUpInside) in segmentChanged method and it works only for buttonOne and messes up others. How do I get proper messages for all buttons and segments when the segment is changed? Thanks in advance.


Solution

  • You need to set your UISegmentedControl method for .valueChange not for .touchUpInside.

    Looks following:

    UISegmentedControl

    and add following method.

    Code:

    @IBOutlet weak var buttonOne            : UIButton!
    @IBOutlet weak var buttonTwo            : UIButton!
    @IBOutlet weak var buttonThree          : UIButton!
    @IBOutlet weak var segmentedControl     : UISegmentedControl!
    
    var selectedButton                      : UIButton!
    
    @IBAction func buttonsTapped(_ sender: UIButton) {
    
        selectedButton = sender
    
        switch sender {
    
        case buttonOne:
            print("Button one Tapped")
    
        case buttonTwo:
            print("Button two tapped")
    
        case buttonThree:
            print("Button three tapped")
    
        default: break
        }
    
        if self.segmentedControl.selectedSegmentIndex == 0 {
            print("First Segment")
        } else {
            print("Second Segment")
        }
    }
    
    
    @IBAction func segmentChanged(_ sender: UISegmentedControl) {
        if sender.selectedSegmentIndex == 0
        {
            self.selectedButton.sendActions(for: .touchUpInside)
        }
        else
        {
            self.selectedButton.sendActions(for: .touchUpInside)
        }
    }