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.