问题
I need different images on each segment of UISegmentController, I tried many solutions in Stackoverflow but none of them satisfied my need. Im new to IOS, So please help me.
Also change image on each selection with some other jpg files.
Presently I'm using this method
UIImage *segmentUnselected =
[UIImage imageNamed:@"26.png"];
[[UISegmentedControl appearance] setBackgroundImage:segmentUnselected
forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
But i want different images for each segment. Any way to do this?
回答1:
Have you tried setting image for each segment based on its segment index? For example, lets say you have three segments in the segmentedControl and want to set three different images for segments. You may do like:
[self.mySegmentedControl setImage:[UIImage imageNamed:@"MYIMAGE1.PNG" forSegmentAtIndex:0];
[self.mySegmentedControl setImage:[UIImage imageNamed:@"MYIMAGE2.PNG" forSegmentAtIndex:1];
[self.mySegmentedControl setImage:[UIImage imageNamed:@"MYIMAGE3.PNG" forSegmentAtIndex:2];
And when you want to change the image on value changed, you can create a method that handles UIControlValueChanged
of your segmentedControl. Like this:
-(void)valueDidChange
{
switch ([self.mySegmentedControl selectedSegmentIndex]) {
case 0:
[self.mySegmentedControl setImage:[UIImage imageNamed:@"SOME_OTHERIMAGE"] forSegmentAtIndex:0];
break;
case 1:
[self.mySegmentedControl setImage:[UIImage imageNamed:@"SOME_OTHERIMAGE"] forSegmentAtIndex:1];
break;
case 2:
[self.mySegmentedControl setImage:[UIImage imageNamed:@"SOME_OTHERIMAGE"] forSegmentAtIndex:2];
break;
default:
break;
}
}
EDIT: And in your viewDidLoad
, you can set an action to your UISegmentedControl
to respond to the method added. Like this,
[self.mySegmentedControl addTarget:self action:@selector(valueDidChange) forControlEvents:UIControlEventValueChanged];
回答2:
Maybe you can have a look at SMSegmentView, which allows you to set image/text for a segment:

Here is the link for this framework. The project page should give you a good idea of how to use it and the source code comes with a sample as well.
来源:https://stackoverflow.com/questions/26522677/how-can-i-get-each-segment-on-uisegmentcontroler-with-diffrent-image