How can i get each Segment on uisegmentcontroler with diffrent image?

人走茶凉 提交于 2019-12-12 02:18:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!