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 –

1
2
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.

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

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

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

5. You can also customize the switches colors

1
2
3
4
5
6
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

1
mySwitch.isRounded = NO;

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

Namit Gupta

iOS Developer @GetVokal. Passionate about Mobile Apps. Loves to Design. You can reach him on his social profiles below.

Leave a Reply