Search code examples
iosios8uisegmentedcontroliboutlet

Handle tap on same segmented button?


I'm trying to handle a tap event on a segmented control, but when the selected button is clicked again. For example, for the screenshot below where "Second" is already selected, how do I handle the action when the "Second" button is clicked again?

I tried an IBOutlet, but it only triggers when the value has changed. Then I tried the code below, but the same thing where it triggers only when the value changes. In both cases while "Second" is selected, clicking "Second" again does not fire anything. Is there a way to do this?

segmentedControl.addTarget(self, action: "segementedAnyTap:", forControlEvents: .AllEvents)

enter image description here


Solution

  • This works for me, adding a gesture recogniser to the UISegmentedControl

    - (void)viewDidLoad
    {
      [super viewDidLoad];
    
      [self.segmentedControl addTarget:self action:@selector(valueChanged:) forControlEvents:UIControlEventValueChanged];
      UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(touched:)];
      [self.segmentedControl addGestureRecognizer:tapGesture];
    }
    
    - (void)valueChanged:(id)sender
    {
      // value change code
    }
    
    - (void)touched:(id)sender
    {
      // code to check if the segmented controls index has not changed.
      // execute desired functionality
    }