-->

Weird behavior with UISegmentedControl and UIAppea

2019-03-20 18:13发布

问题:

I am setting the appearance of the segmented control via these statements in the app delegate.

    [[UISegmentedControl appearance] setBackgroundImage:[[UIImage imageNamed:@"segmentation_normal.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0 , 0, 0)] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    [[UISegmentedControl appearance] setBackgroundImage:[[UIImage imageNamed:@"segmentation_selected.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0 , 0, 0)] 
        forState:UIControlStateSelected barMetrics:UIBarMetricsDefault];

    [[UISegmentedControl appearance] setDividerImage:[UIImage imageNamed:@"segmentation_divider_NormalNormal.png"]   forLeftSegmentState:UIControlStateNormal rightSegmentState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    [[UISegmentedControl appearance] setDividerImage:[UIImage imageNamed:@"segmentation_divider_NormalSelected.png"] forLeftSegmentState:UIControlStateNormal rightSegmentState:UIControlStateSelected barMetrics:UIBarMetricsDefault];
    [[UISegmentedControl appearance] setDividerImage:[UIImage imageNamed:@"segmentation_divider_SelectedNormal.png"] forLeftSegmentState:UIControlStateSelected rightSegmentState:UIControlStateNormal barMetrics:UIBarMetricsDefault];

The result is fine. Backgrounds and dividers are set correctly when I select any of the segments (the Order segment is selected by Default when the app first launches). When I select the Release segment as you can see below everything looks fine.

The problem is when I go out of the view then back to the view (I store the selected index and set it in the viewDidLoad to reselect the segment), the divider is set incorrectly for some unknown reason.

If I tap on A-Z then Release, it corrects itself. This bug only occurs when the view first loads and the selected segment was either Release or A-Z. The divider always looks fine when Order is selected and the view loads.

Image sizes: the divider is 2px wide (all 3 images are the same size), the backgrounds are 2 px wide each.

Any ideas or pointers would be highly appreciated, I have been pulling my hair for the past 10 hours trying to find a solution to no available.

回答1:

This is a bug with UISegmentedControl, I think. You can work around it by setting the selected segment after a delay, to allow the control time to draw itself. You don't even have to use an actual delay, just something like:

[self performSelector:@selector(setPreferences) withObject:nil afterDelay:0.0];

Where setPreferences updates the value of your segmented control.