Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UISegmentedControl: how to detect click on current segment?

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

like image 656
hzxu Avatar asked Nov 12 '13 01:11

hzxu


2 Answers

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"

like image 192
Ariven Nadar Avatar answered Oct 21 '22 09:10

Ariven Nadar


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.

like image 37
Vincent Bernier Avatar answered Oct 21 '22 09:10

Vincent Bernier