10

is there a way to detect second click on a segment in UISegmentedControl? I found:

Detect second click on a segment

however, it is stated that:

If you set a segmented control to have a momentary style, a segment doesn’t show itself as selected (blue background) when the user touches it. The disclosure button is always momentary and doesn’t affect the actual selection.

Is there a way to detect second click as well as trigger the selection action and show the segment as selected?

If there is no straight forward way to do it, what I was thinking, is that I first have the momentary flag set to YES, then upon each click, manually update the selection state, but then I also need to update/deselect other segments.

Thanks

Community
  • 1
  • 1
Heuristic
  • 5,087
  • 9
  • 54
  • 94

2 Answers2

16

The solution is to have a custom subclass of UISegmentedControl and check it yourself like this.

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    current = self.selectedSegmentIndex;
    [super touchesBegan:touches withEvent:event];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesEnded:touches withEvent:event];

    if (current == self.selectedSegmentIndex)
        [self sendActionsForControlEvents:UIControlEventValueChanged];
}

I had an other solution all in touchesBegan, but it's not working anymore in iOS 7. There is also other solution on Stack Overflow that are not working in iOS 6 and greater.

Vincent Bernier
  • 8,674
  • 4
  • 35
  • 40
  • 1
    Most of the solutions I've tried so far would trigget the selection event two times, this works perfectly on iOS 7. You are the best, thank you! – Thiago Peres Nov 24 '13 at 01:19
1

To make a particular segment click-able again is not possible, but you can reset the whole segmentControl using UISegmentedControlNoSegment.

[self.segmentCtrlOutlet setSelectedSegmentIndex:UISegmentedControlNoSegment];

what you have to do is put the above code in the place where that code executes when you click on a particular segment of UISegmentedControl.

for eg. In my project when I click on a segment, UIPopoverController opens up and inside it I have UIPicker, so I use the above code in UIPicker delegate method "didSelectRow"

Visual Vincent
  • 18,045
  • 5
  • 28
  • 75
Ariven Nadar
  • 1,278
  • 13
  • 13
  • Isn't this the same as making the control momentary? I don't think it solves the question, since the OP wants to detect a click on a segment that is already selected. https://developer.apple.com/documentation/uikit/uisegmentedcontrol/1618586-ismomentary – Michael Peterson Nov 16 '17 at 04:22