22

It looks like this whenever off:

enter image description here

While I'd prefer more of a grey background. Do I really have to use a UIImageView?

Doug Smith
  • 29,668
  • 57
  • 204
  • 388

6 Answers6

53

Here is how I changed the fill color of my iOS7 UISwitch.

First you need to import QuartzCore.

#import <QuartzCore/QuartzCore.h>

Then set the background color and round the UISwitch's corners.

UISwitch *mySwitch = [[UISwitch alloc] initWithFrame:CGRectMake(0.0, 0.0, 51.0, 31.0)];
mySwitch.backgroundColor = [UIColor redColor];
mySwitch.layer.cornerRadius = 16.0; // you must import QuartzCore to do this.
[self addSubview:mySwitch];

This will give you a UISwitch with a custom off (background) color.

Hope this helps someone:)

Barry Wyckoff
  • 614
  • 5
  • 10
17

You can set the setOnTintColor property of your UISwitch to the color you desire.

Antonio R.
  • 407
  • 3
  • 9
6

You can also set this for the switch in Interface Builder. Just set the background colour of the UISwitch to whatever colour you want (white, in the example below), then set a User Defined Runtime Attribute of layer.cornerRadius = 16:

enter image description here

Stewart Macdonald
  • 2,062
  • 24
  • 27
4

There's no API support for changing the off fill color of a UISwitch.

Adjusting the tintColor will only affect the outline, and adjusting the backgroundColor will affect the whole frame, including the parts outside the rounded bounds.

You either have to place a properly shaped opaque UIView behind it or - easier - use a custom open source implementation, such as MBSwitch, which allows you to set the off fill color.

Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235
3

You can also use an image as background, using the [UIColor colorWithPatternImage];

mySwitch.onTintColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"toggle-bg-on"]];
mySwitch.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"toggle-bg-off"]];
1

Adding to Barry Wyckoff solution : set tint color also

UISwitch *mySwitch = [[UISwitch alloc] initWithFrame:CGRectMake(0.0, 0.0, 51.0, 31.0)];
mySwitch.backgroundColor = [UIColor redColor];
mySwitch.layer.cornerRadius = 16.0; // you must import QuartzCore to do this.
mySwitch.tintColor = [UIColor redColor];
[self addSubview:mySwitch];