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;

}

}

});

}

6 comments

  1. Ram · December 13, 2012

    it is working…thanks for info

  2. fogwolf · March 5, 2013

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

    Thanks.

    • kmdarshan · March 5, 2013

      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.

      • fogwolf · March 5, 2013

        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 · March 5, 2013

    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 · July 29, 2013

    Thanks it is great solutoins

Leave a reply to fogwolf Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.