Customizing UISegmentedControl in iOS 5

nimeshdesai picture nimeshdesai · Feb 2, 2012 · Viewed 21.4k times · Source

Here is my problem. I am customizing a UISegmentedControl by setting the background and divider images in the following way:

[[UISegmentedControl appearance] setDividerImage:segmentUnselectedUnselected forLeftSegmentState:UIControlStateNormal rightSegmentState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
[[UISegmentedControl appearance] setDividerImage:segmentSelectedUnselected forLeftSegmentState:UIControlStateSelected rightSegmentState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
[[UISegmentedControl appearance] setDividerImage:segUnselectedSelected forLeftSegmentState:UIControlStateNormal rightSegmentState:UIControlStateSelected barMetrics:UIBarMetricsDefault];

[[UISegmentedControl appearance] setBackgroundImage:segmentUnselected forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
[[UISegmentedControl appearance] setBackgroundImage:segmentSelected forState:UIControlStateSelected barMetrics:UIBarMetricsDefault];

When I try to make the 1st segmented selected within viewDidLoad

self.segmentedControl.selectedIndex = 1;

I get the following weird thing:

enter image description here

instead of:

enter image description here

Does anyone know if this is a bug and how could I provide a bug report? If not, what could be wrong with my code?

Answer

Fernando Madruga picture Fernando Madruga · Mar 15, 2012

After doing some tests and trying several different locations for the customization, I believe this may indeed be a bug.

Even with a very simple straight UISegmentedControl, this is what I get (using Xcode 4.3.1, iOS 5.1):

After launching and selecting the middle element in code: After launching and selecting the middle element in code

After user-clicked away and clicking back on middle element: After user-clicked away and clicking back on middle element

I used 3px wide images for the separators and 1px wide images for the backgrounds.

Edit: I think I found a workaround: try queueing the instruction to select the element, rather than executing it in viewDidLoad, like this:

dispatch_async(dispatch_get_main_queue(),^{
   self.segmentedControl.selectedSegmentIndex = 1;
});

On my example above, queuing that instruction makes it work just fine.