Sheehan Alam
Sheehan Alam

Reputation: 60859

UISegmentedControl does not detect segment change in iOS5

I have a UISegmentedControl

UIBarButtonItem *flex = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]autorelease];
    bottomSegmentedControl = [[UISegmentedControl alloc] initWithItems:nil];
    [bottomSegmentedControl insertSegmentWithImage:[UIImage imageNamed:@"messages.png"] atIndex:0 animated:YES];
    [bottomSegmentedControl insertSegmentWithImage:[UIImage imageNamed:@"news.png"] atIndex:1 animated:YES];
    [bottomSegmentedControl insertSegmentWithImage:[UIImage imageNamed:@"chart.png"] atIndex:2 animated:YES];
    //bottomSegmentedControl = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"Messages",@"News",@"Chart", nil]];
    //bottomSegmentedControl.tintColor = [UIColor blackColor];
    [bottomSegmentedControl addTarget:self action:@selector(segmentedControlChanged:)forControlEvents:UIControlEventValueChanged];
    bottomSegmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
    bottomSegmentedControl.frame = CGRectMake(0,0,300,30);
    bottomSegmentedControl.momentary = NO;
    [bottomSegmentedControl setSelectedSegmentIndex:0];
    UIBarButtonItem *segButton = [[UIBarButtonItem alloc] initWithCustomView:bottomSegmentedControl];

When I step through the program [bottomSegmentedControl setSelectedSegmentIndex:0]; does not trigger a UIControlEventValueChanged event which is where I do some stuff in segmentedControlChanged:

This used to work in iOS 4.3 but not in iOS5. How can I resolve this?

Upvotes: 3

Views: 2608

Answers (2)

Ric Santos
Ric Santos

Reputation: 16437

This question has been answered here: https://stackoverflow.com/a/8054774/883413

In iOS5 the events from a UISegmentedControl are no longer fired if the value is changed programatically, to keep consistency with the behaviour of other UIControls.

A quick solution is to add:

[bottomSegmentedControl sendActionsForControlEvents:UIControlEventValueChanged];

after

[bottomSegmentedControl setSelectedSegmentIndex:0];

however it will call your selector

segmentedControlChanged:

twice in iOS<5

Upvotes: 5

Caleb
Caleb

Reputation: 124997

This seems to be a known issue. It's not clear whether Apple considers the new behavior to be a feature or a bug.

Upvotes: 1

Related Questions