How to change UISwitch default color for OFF state?

Sam Shaikh picture Sam Shaikh · Sep 2, 2014 · Viewed 16.9k times · Source

I want to change the color of onTintColor in the UISwitch for the off State. The switch is in tableview and switch is made programmatically.

    [settingsSwitch setBackgroundColor:[UIColor whiteColor]];
    [settingsSwitch setTintColor:[UIColor whiteColor]];
    [settingsSwitch setThumbTintColor:[UIColor redColor]];
    [settingsSwitch setOnTintColor:[UIColor colorWithRed:138/256.0  green:9/256.0 blue:18/256.0 alpha:1]];

enter image description here

This is the result i get when i set the background color white.

enter image description here

And without background i get red color which is the color of my cell.

enter image description here

and this is the result i want, when switch is on the onTintColor should b dark red, and in off state it should be white.

i tried setting the image on switch with this line of code

[settingsSwitch setOnImage:[UIImage imageNamed:@"on.png"]];
[settingsSwitch setOffImage:[UIImage imageNamed:@"off.png"]];

But its not changing the images. i want to change the color of switch in off state. Hope i have explained my question clearly.thanks for helping in advance.

Answer

Chatar Veer Suthar picture Chatar Veer Suthar · Sep 2, 2014

You can use following CODE to fulfill requirement.

Your ViewDidLoad

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    [self.view setBackgroundColor:[UIColor redColor]];

    settingsSwitch.layer.cornerRadius = 16.0; // you must import QuartzCore to do this


    if (settingsSwitch.on) {
        NSLog(@"If body ");
        [settingsSwitch setThumbTintColor:[UIColor redColor]];

        [settingsSwitch setBackgroundColor:[UIColor whiteColor]];
        [settingsSwitch setOnTintColor:[UIColor whiteColor]];

    }else{
        NSLog(@"Else body ");

        [settingsSwitch setTintColor:[UIColor clearColor]];

        [settingsSwitch setThumbTintColor:[UIColor redColor]];

        [settingsSwitch setBackgroundColor:[UIColor colorWithRed:138/256.0 green:9/256.0 blue:18/256.0 alpha:1]];
    }
}

Method where status change IBAction is called.

- (IBAction)switchStatusChange:(UISwitch *)sender
{
    if (sender.on) {
        NSLog(@"If body ");
        [sender setThumbTintColor:[UIColor redColor]];

        [sender setBackgroundColor:[UIColor whiteColor]];
        [sender setOnTintColor:[UIColor whiteColor]];

    }else{
        NSLog(@"Else body ");

        [sender setTintColor:[UIColor clearColor]];

        [sender setThumbTintColor:[UIColor redColor]];

        [sender setBackgroundColor:[UIColor colorWithRed:138/256.0 green:9/256.0 blue:18/256.0 alpha:1]];
    }
}