tags:

views:

630

answers:

2

I have a UISegmentedControl which I'd like to use to perform a certain action if you click the already selected item.

My thinking is basically something like this:

- (void)viewDidLoad {
    UISegmentedControl * testButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"one", @"two", nil]];
    [self.view addSubview:testButton];
    [testButton addTarget:self action:@selector(clicked:) forControlEvents:UIControlEventTouchUpInside];
    [super viewDidLoad];
}

-(void) clicked: (id) sender{
    NSLog(@"click");
}

(And in clicked: I'd just do some check to see if the new selected index is different from the old selected index before the click)

The problem is I can't seem to override the action for the TouchUpInside control event. Any help appreciated!

-S

A: 

Use UIControlEventValueChanged with UISegmentedControls.

Corey Floyd
The problem with that is if the value has changed then obviously the user hasn't touched the item that's already selected.
spencewah
A: 

You can use a subclass to get the behavior you want. Make a subclass of UISegmentedControl that has one BOOL ivar:

BOOL _actionSent;

Then, in the implementation, override the following two methods:

- (void)sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event {
    [super sendAction:action to:target forEvent:event];
    _actionSent = TRUE;
}

- (void) setSelectedSegmentIndex:(NSInteger)toValue {
    _actionSent = FALSE;

    [super setSelectedSegmentIndex:toValue];

    if (!_actionSent) {
        [self sendActionsForControlEvents:UIControlEventValueChanged];
        _actionSent = TRUE;
    }
}

There are probably other ways but this worked ok for me. I'd be interested to learn of other approaches.

Chris Walters