Answering a StackOverFlow question regarding UISegmentedControl

Question: I have a segmented control with 8 segments. I can change the default tintColor of the whole control, BUT can I set a different color for each segment in the control? I found a tutorial that worked in 5.1 with a new class that calls this method, “-(void)setTintColor:(UIColor*)color forTag:(NSInteger)aTag” But it doesn’t work in iOS 6. Any ideas?

Answer:

Its a hacky fix. This will work. Place your code in ViewDidAppear. That will do the trick.


- (void)viewDidAppear:(BOOL)animated

{

[super viewDidAppear:animated];

dispatch_async(dispatch_get_main_queue(),^{

for (int i=0; i<[segmentControl.subviews count]; i++)

{

if ([[segmentControl.subviews objectAtIndex:i]isSelected] )

{

[[segmentControl.subviews objectAtIndex:i] setTintColor:[UIColor blackColor]];

break;

}

}

});

}

About these ads

6 thoughts on “Answering a StackOverFlow question regarding UISegmentedControl

    • I am not sure, if this would answer your question. I am trying load the view first, and then use an async call with the main queue to set the color.

      • Thanks. Just not sure why it has to be done asynchronously – it doesn’t work otherwise, or at least didn’t when I tried. Is the issue that for some reason in this case the view needs to be loaded first? Though using async order still isn’t guaranteed, right? I would assume if you want to do it after the view has loaded but do not want it to execute every time the view loads you would do this instead of putting it in viewWillAppear?

  1. Yeah, I know its a bit confusing here. But this is just my assumption to whats happening here. When we do an async call, that part is backgrounded, and is executed only after the viewDidAppear completes in the main thread. Once the viewDidAppear is completed, we use the main queue to set the tint color. At the end of the day, this is just a hack or bug, there might be a better way to fix it. Thanks for reading..

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s