Question

I have a UISegmentedControl that I want to appear in an UIToolbar. It appears, but clicking it does not call the method that it should. Am I missing anything?

Code:

-(void)setupToolbars{
    NSArray *segItemsArray = [NSArray arrayWithObjects: @"List", @"Day", @"Month", nil];
    segmentedControl = [[UISegmentedControl alloc] initWithItems:segItemsArray];
    segmentedControl.selectedSegmentIndex = 2;
    [segmentedControl addTarget:self action:@selector(changeView) forControlEvents:UIControlEventTouchUpInside];//this line should make the segmented control call the correct method
    UIBarButtonItem *segmentedControlButtonItem = [[UIBarButtonItem alloc] initWithCustomView:(UIView *)segmentedControl];
    NSArray *barArray = [NSArray arrayWithObjects: todayButtonItem,flexibleSpace, segmentedControlButtonItem, flexibleSpace, nil];
    [bottomToolbar setItems:barArray];
}
-(void)changeView{
    NSLog(@"changeView");
    ...
}
Was it helpful?

Solution

You want to use the UIControlEventValueChanged event, not the UIControlEventTouchUpInside event.

OTHER TIPS

Just building on top of what rmaddy stated. I would also suggest use of UIControlEventValueChanged event.

[segmentedControl addTarget:self action:@selector(didChangeSegmentControl:) forControlEvents:UIControlEventValueChanged];


-(void)didChangeSegmentControl:(UISegmentedControl*) control
{
    if (control.selectedSegmentIndex ==0 )
    { 
          //...
    }
}  
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top