Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
447 views
in Technique[技术] by (71.8m points)

objective c - Customizing UISegmentedControl in iOS 5

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...