How to Create Custom Switch Control View – XCode iOS

You use the UISwitch class to create and manage the On/Off buttons used, for example, in the Settings app for options such as Airplane Mode and Bluetooth. These objects are known as switches. -Apple

custom switch control xcodeXCode has no option to change the shape and size of the default UISwitch button. If you need to create a customised UISwitch you can use SevenSwitch.

There are other similar libraries (DCRoundSwitch) but the best part of SevenSwitch is that it supports iOS7 UISwitch style and offers many customisation options.

Customisations offered – Image for on/off state, customise switch color (active, inactive, border, onTintcolor, shadow) and you can even make it square corners instead of round.

How to use (via GitHub) –

1. Add SevenSwitch.h and SevenSwitch.m files to your project and add the QuartzCore framework to your project.

2. Initializing and adding the switch to the screen –

SevenSwitch *mySwitch = [[SevenSwitch alloc] initWithFrame:CGRectMake(10, 10, 50, 30)];
[self.view addSubview:mySwitch];

3. When the user manipulates the switch control (“flips” it) a UIControlEventValueChanged event is generated.

[mySwitch addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];

4. You can set images for the on/off states

mySwitch.offImage = [UIImage imageNamed:@"cross.png"];
mySwitch.onImage = [UIImage imageNamed:@"check.png"];

5. You can also customize the switches colors

mySwitch.thumbTintColor = [UIColor colorWithRed:0.19f green:0.23f blue:0.33f alpha:1.00f];
mySwitch.activeColor = [UIColor colorWithRed:0.07f green:0.09f blue:0.11f alpha:1.00f];
mySwitch.inactiveColor = [UIColor colorWithRed:0.07f green:0.09f blue:0.11f alpha:1.00f];
mySwitch.onTintColor = [UIColor colorWithRed:0.45f green:0.58f blue:0.67f alpha:1.00f];
mySwitch.borderColor = [UIColor clearColor];
mySwitch.shadowColor = [UIColor blackColor];

6. You can turn off the rounded look by setting the isRounded property to NO

mySwitch.isRounded = NO;

Please share if you know of any other good library for the same.

Published by Namit Gupta

Technical Lead iOS @ONEChampionship | Ex-SDE2 @ Halodoc, Ex-iOS Lead @ Vokal. ❤️ Swift, designing pixel-perfect UI and writing clean code. Check my portfolio here.

Leave a comment

Your email address will not be published. Required fields are marked *