I have a segmented control and I want first and last items to be of specified width (say, wider than others). When I setWidth:forSegmentAtIndex: for standard-styled segmentedControl (i.e. [[UISegmantedControl appearence] setBackgroundImage:forState:barMetrics:] not set), things behave themselves as they should. But when I set background image, segments width doesn’t change.
Here is my code:
[[UISegmentedControl appearance] setBackgroundImage:[[UIImage imageNamed:@"btn_normal.png"] stretchableImageWithLeftCapWidth:25 topCapHeight:0] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
[[UISegmentedControl appearance] setBackgroundImage:[[UIImage imageNamed:@"btn_selected.png"] stretchableImageWithLeftCapWidth:25 topCapHeight:0] forState:UIControlStateSelected barMetrics:UIBarMetricsDefault];
[[UISegmentedControl appearance] setDividerImage:[UIImage imageNamed:@"nn.png"] forLeftSegmentState:UIControlStateNormal rightSegmentState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
[[UISegmentedControl appearance] setDividerImage:[UIImage imageNamed:@"sn.png"] forLeftSegmentState:UIControlStateSelected rightSegmentState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
[[UISegmentedControl appearance] setDividerImage:[UIImage imageNamed:@"ns.png"] forLeftSegmentState:UIControlStateNormal rightSegmentState:UIControlStateSelected barMetrics:UIBarMetricsDefault];
[self.segmentedControl setContentMode:UIViewContentModeScaleToFill];
[self.segmentedControl setWidth:100.0 forSegmentAtIndex:0];
[self.segmentedControl setWidth:100.0 forSegmentAtIndex:4];
With this, all my segments appear automatically sized to the equal width.
And when I comment out all above this
[self.segmentedControl setContentMode:UIViewContentModeScaleToFill];
[self.segmentedControl setWidth:100.0 forSegmentAtIndex:0];
[self.segmentedControl setWidth:100.0 forSegmentAtIndex:4];
the sizes are set correctly.
Here is my question: how can I set sizes for the segments with background images?
I’m new to cocoa-touch and objective-c, so I might be missing something…
Could you help please?
I think when you use [UISegmentedControl appearance] proxy it overrides “setWidth:forSegmentAtIndex:” method values. So possible solutions:
1)
I would not recommend to use this because it will set custom width for 0 and 4 segments for every segmented control in your app.
2)
If you need that all segmented controls in your app should have custom background then I would recommend to write your own proxy method. Something like this: