6

I created a UISwitch using this code...

UISwitch *switch = [[UISwitch alloc]initWithFrame:CGRectMake(110, 230, 60, 60)];
[window addSubview:switchView];
[switchView release];

The created button will be....

enter image description here

The default properties are,

  1. It contains "ON" & "OFF" states
  2. The OFF button is white & the ON button is in blue color

I want to create a customized switch, so that the background color & text in the switch should be changed. Is it possible? Please explain in detail.

Thanks in Advance,

Rajkanth

2 Answers2

20

You can not modify UISwitch control unless and until you write your own control,

But best way so far, you can used UISegmentControl and handle event on it to switch the on.png and off.png images.

UISegmentedControl* switchView=[[UISegmentedControl alloc] initWithItems:[[[NSMutableArray alloc] initWithObjects:@"On",@"Off",nil] autorelease]];
    [switchView setFrame:CGRectMake(20,365,140,28)];
    switchView.selectedSegmentIndex=0;
    switchView.segmentedControlStyle=UISegmentedControlStyleBar;
    [switchView setImage:[UIImage imageNamed:@"onSelected.png"] forSegmentAtIndex:0];
    [switchView setImage:[UIImage imageNamed:@"off.png"] forSegmentAtIndex:1];
    [switchView addTarget:self action:@selector(checkOnOffState:) forControlEvents:UIControlEventValueChanged];

    self.navigationItem.titleView=switchView;

and write checkOnOffState method code like this-

-(IBAction)checkOnOffState:(id)sender{

    UISegmentedControl* tempSeg=(UISegmentedControl *)sender;
    if(tempSeg.selectedSegmentIndex==0){
        [tempSeg setImage:[UIImage imageNamed:@"onSelected.png"] forSegmentAtIndex:0];
        [tempSeg setImage:[UIImage imageNamed:@"off.png"] forSegmentAtIndex:1];
    }
    else{
        [tempSeg setImage:[UIImage imageNamed:@"on.png"] forSegmentAtIndex:0];
        [tempSeg setImage:[UIImage imageNamed:@"offSelected.png"] forSegmentAtIndex:1];
    }   
}
Mayur Birari
  • 5,837
  • 8
  • 34
  • 61
  • 1
    what's the difference between the onSelected.png image and the on.png image? Is the "selected" bit the actual knob and the on/off.png is the track? – Greg Combs Feb 24 '11 at 02:39
  • Is there any restriction on the size of the image which we can set? My image is coming in the center of the segment and is not utilizing the full space. Any help would be appreciated. – megha Dec 11 '14 at 10:15
2

I used this solution: UICustomSwitch: it works customizing a UISlider and setting a max valure of 1.

You can change the images of your switch, the right / left text and use it with a unique color on background (if you don't want to use images).

The only change I did was about the name: UI is reserved for Apple classe, so I changed it for my own.

Marco Pace
  • 3,820
  • 19
  • 38