0

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?

  • Do you try this: http://stackoverflow.com/questions/10740373/setting-background-image-of-uisegmentedcontrol – scottphc Oct 23 '14 at 07:03

2 Answers2

0

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];
GenieWanted
  • 4,473
  • 4
  • 24
  • 35
  • You will need to handle this in your .m file by adding an action to your UISegmentedControl.. I have edited the answer. Please see the updated one above. – GenieWanted Oct 23 '14 at 11:11
  • But I want to set image for "forState:UIControlStateNormal and "UIControlStateSelected". setImage does not work with this property. – sachin sachu Oct 23 '14 at 11:13
0

Maybe you can have a look at SMSegmentView, which allows you to set image/text for a segment:

Screenshot

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.

Community
  • 1
  • 1
Elias Ma
  • 106
  • 4