views:

22

answers:

1

I want to register a function on a UISegmentedControl for the event UIControlEventTouchUpInside -- not UIControlEventValueChanged. I specifically want to ensure that it fires only when the user touches within the item, not when its value is set programmatically.

Any suggestions?

+1  A: 

The key, I found, is to subclass UISegmentedControl. Under normal condition, UISegmentedControl simply doesn't respond to UIControlEventTouchUpInside. By subclassing UISegmentedControl, you can redefine the function touchesEnded (which essentially is what gets fired when the user touches an object) as such:

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesEnded:touches withEvent:event];
    [self.superview touchesEnded:touches withEvent:event];

    MyViewController *vc; // the view controller which contains the UISegmentedControl
    for (UIView* next = [self superview]; next; next = next.superview) {
        UIResponder* nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[MyViewController class]]) {
            vc = (MyViewController*)nextResponder;
            break;
        }
    }

    if (vc) {
        [vc myFunction];
    }
} 
Jason