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.
[sourcecode language=”objc”]
– (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;
}
}
});
}
[/sourcecode]

6 responses

  1. it is working…thanks for info

  2. Why do you have to use dispatch_async. Just tried it and it does not work without this. Not sure why.
    Thanks.

    1. kmdarshan Avatar
      kmdarshan

      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.

      1. 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?

  3. kmdarshan Avatar
    kmdarshan

    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..

  4. Brijesh Bosamiya Avatar
    Brijesh Bosamiya

    Thanks it is great solutoins

Leave a Reply

Your email address will not be published. Required fields are marked *