Saturday, April 6, 2013

Free Custom UISwitch - Flexible Colors and Size

What's up wonderful people?

This is NOT a tutorial. :D

However there is a downloadable Sample Code. I'd like to give away this little custom UISwitch-like class I made. I realize there are already other custom UISwitches that are cool (like, however mine consists of simple readily available UIControls like UIViews and UILabels, and it has MORE FLEXIBILITY in its components.
Also, since this component is created entirely on UIKit, it will look nice in all resolution (retina or not), ipad or whatever.

Here is the screenshot of samples of custom UISwitch that can be created with this class:

Using this class is simple.

1. Copy Switchy.h and Switchy.m to your folder and add them to your project.
Then import the Switchy.h in your viewcontroller's header.

#import "Switchy.h"

2. Add QuartzCore.framework to your project.

2. Declare the switch it in your header.

Switchy *mySwitch;

3. Create it in viewDidLoad and customize everything in the initWithFrame custom method.

mySwitch = [[Switchy alloc] initWithFrame:CGRectMake(0, 0, 79, 27) withOnLabel:@"ON" andOfflabel:@"OFF"
                     withContainerColor1:[UIColor colorWithRed:0.1 green:0.7 blue:1.0 alpha:1.0]
                      andContainerColor2:[UIColor colorWithRed:0.1 green:0.7 blue:0.9 alpha:1.0]
                          withKnobColor1:[UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0]
                           andKnobColor2:[UIColor colorWithRed:0.7 green:0.7 blue:0.7 alpha:1.0] withShine:YES];

4. Hook a method of your own when user toggles the switch:

[sw1 addTarget:self action:@selector(customMethod) forControlEvents:UIControlEventTouchUpInside];

5. Add to your viewcontroller's view and position it anywhere.

[self.view addSubview:sw1]; = CGPointMake(160, 50);

Feel free to modify the Switchy.m and .h to your liking (add a border, or other things).
Switchy Class is provided for 100% Free.




  1. Fantastic! Just what I was looking for!! Thanks, Emir. Downloaders should note that you can tailor the switch to your needs by changing the width of the knob or the size of the font, or shifting the labels left or right a little.

  2. Hey thanks for checking out my blog. And glad that you like this custom UISwitch class!

  3. This comment has been removed by the author.

  4. Hello. Your code is very helpful. but I found mistake in initWithFrame method. In line container = [[UIView alloc] initWithFrame:CGRectMake(frame.origin.x, frame.origin.x, frame.size.width, frame.size.height)]; - you twice used frame.origin.x instead of use zero.
    Correct version of this row is container = [[UIView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
    Yours sincerely, Mikhail.

  5. awesome job.. i would lv to be your friend.. keep in touch