How to change the default color of UISwitch to OFF?

I want to change the color of onTintColor in UISwitch to off. The switch is in table view mode, and the software switch is done.

[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 that I get when I set the background color to white.

enter image description here

And without the background, I get a red color, which is the color of my cell.

enter image description here

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

I tried to set the image on the switch using this line of code

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

But he does not change the image. I want to change the color of the switch off. Hope I explained my question clearly. Thanks for the help in advance.

+6
source share
3 answers

You can use the following CODE to fulfill the 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]]; } } 

The method in which the IBAction status change 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]]; } } 
+7
source

You can use the first approach + add a frame radius to remove unwanted corners:

 slider.backgroundColor = [UIColor whiteColor]; slider.layer.cornerRadius = 18.0; 

Originally from this answer.

+3
source

UISwitch's corner cuts out the view and doesn't see the rounded, the best answer here is https://stackoverflow.com/a/38564168/6609238

+1
source

Source: https://habr.com/ru/post/974673/


All Articles