How do I make a UISwitch under iOS 7 not take the background colour of the view behind it?
Solution 1
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:)
Solution 2
You can set the setOnTintColor
property of your UISwitch
to the color you desire.
Solution 3
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
:
Solution 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.
Solution 5
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"]];
Related videos on Youtube
Doug Smith
I'm a web designer playing around with iOS from England
Updated on June 26, 2022Comments
-
Doug Smith almost 2 years
It looks like this whenever off:
While I'd prefer more of a grey background. Do I really have to use a UIImageView?
-
Doug Smith over 10 yearsThis refers to when it's off.
-
ICL1901 over 10 yearsFor me, this setting refers to when the switch is on. e.g.: [usePatternsSwitch setOnTintColor: [UIColor lightGrayColor]];
-
The dude almost 10 yearsThe day they change the shape of the switch your solution will not look fine.
-
Stefano Mondino over 9 yearsThe day they will change the shape of the switch I will have to recompile the app with the new SDK and then I'll change it.
-
Alex over 8 yearsDown vote, because this doesn't answer the question at all. The question is referring to the off state.
-
coskukoz over 7 yearsVery useful! Better to add swift version too.
-
Alexo Po. over 3 yearsJust extra thanks for pointing that properties may be set with User Defined list, not just in code.