I have a UISegmentedControl containing 3 options for selecting map type. I am setting tintcolor as black as default and I want to set green color for selected segment.
Here is declaration of segmented control
NSArray *mapType = [NSArray arrayWithObjects: @"Map", @"Hyb", @"Sat", nil];
segmentedMapType = [[UISegmentedControl alloc] initWithItems:mapType] ;
segmentedMapType.segmentedControlStyle = UISegmentedControlStyleBar ;
segmentedMapType.tintColor = [UIColor blackColor];
segmentedMapType.frame = CGRectMake(100, 40, 120, 40);
// segmentedMapType.momentary = YES;
[[[segmentedMapType subviews]objectAtIndex:0] setTintColor:[UIColor colorWithRed:0 green:.6 blue:0 alpha:1]];
[segmentedMapType setSelectedSegmentIndex:0];
[segmentedMapType addTarget:self action:@selector(selectMap:) forControlEvents:UIControlEventValueChanged];
[mapSettingsView addSubview:segmentedMapType];
And here is the selector method
-(void)selectMap:(id)sender
{
int index = [segmentedMapType selectedSegmentIndex];
UIColor *newSelectedTintColor = [UIColor colorWithRed: 0 green:.6 blue:0 alpha:1.0];
if (index==0) {
[[[segmentedMapType subviews] objectAtIndex:2] setTintColor:newSelectedTintColor];
[[[segmentedMapType subviews] objectAtIndex:1] setTintColor:[UIColor blackColor]];
[[[segmentedMapType subviews] objectAtIndex:0] setTintColor:[UIColor blackColor]];
} else if (index==1){
[[[segmentedMapType subviews] objectAtIndex:1] setTintColor:newSelectedTintColor];
[[[segmentedMapType subviews] objectAtIndex:0] setTintColor:[UIColor blackColor]];
[[[segmentedMapType subviews] objectAtIndex:2] setTintColor:[UIColor blackColor]];
}
else
if (index==2)
{
[[[segmentedMapType subviews] objectAtIndex:0] setTintColor:newSelectedTintColor];
[[[segmentedMapType subviews] objectAtIndex:1] setTintColor:[UIColor blackColor]];
[[[segmentedMapType subviews] objectAtIndex:2] setTintColor:[UIColor blackColor]];
}
}
This code works good on devices < iOS-5 but on >=iOS-5 problem with this is green tint color does not get applied to correct segment or sometimes to any segment. What is wrong with this code? Any help will be greatly appreciated.
Thanks to this question.
As mentioned there selected index is not a reliable way to assign tintcolor. I had to store their id and use them to assign tintcolor. First store the IDs
And then use it