How to customize UISwitch button in iphone?

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];
    }   
}

Leave a Comment