UISegmentedControl selected state icon image
[segmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
-(void)segmentAction:(UISegmentedControl*)sender {
[sender setImage:[UIImage imageNamed:@"image.png"] forSegmentAtIndex:sender.selectedSegmentIndex];
}
[segmentedControl setBackgroundImage:image
forState:UIControlStateSelected
barMetrics:UIBarMetricsDefault]
You also have to set an image for UIControlStateNormal
for this to take effect.
Apple documentation
Here I created two UISegmentedControl elements programmatically u can set image icon.
UISegmentedControl *switchView=[[UISegmentedControl alloc] initWithItems:[[[NSMutableArray alloc] initWithObjects:@"Yes",@"No",nil] autorelease]];
[switchView setFrame:CGRectMake(180,802,94,27)];
switchView.selectedSegmentIndex=1;
switchView.segmentedControlStyle=UISegmentedControlStyleBar;
[switchView setImage:[UIImage imageNamed:@"switchBlueBg.png"] forSegmentAtIndex:0]; // set icon for when selected
[switchView setImage:[UIImage imageNamed:@"switchOffPlain.png"] forSegmentAtIndex:1]; //set icon for when unselected
[switchView addTarget:self action:@selector(checkOnOffState:) forControlEvents:UIControlEventValueChanged];
[scrollview addSubview:switchView];
UISegmentedControl *switchView1=[[UISegmentedControl alloc] initWithItems:[[[NSMutableArray alloc] initWithObjects:@"Yes",@"No",nil] autorelease]];
[switchView1 setFrame:CGRectMake(180,1003,94,27)];
switchView1.selectedSegmentIndex=1;
switchView1.segmentedControlStyle=UISegmentedControlStyleBar;
[switchView setImage:[UIImage imageNamed:@"switchBlueBg.png"] forSegmentAtIndex:0]; // set icon for when selected
[switchView setImage:[UIImage imageNamed:@"switchOffPlain.png"] forSegmentAtIndex:1]; ////set icon for when unselected
[switchView1 addTarget:self action:@selector(checkOnOffState1:) forControlEvents:UIControlEventValueChanged];
[scrollview addSubview:switchView1];
-(IBAction)checkOnOffState:(id)sender
{
UISegmentedControl* tempSeg=(UISegmentedControl *)sender;
if(tempSeg.selectedSegmentIndex==0)
{
//your codes
}
else
{
//your codes
}
}