Photoshop For Developers: Creating a Custom UISwitch

Tope Abayomi Tope Abayomi
Learn how to create custom UISwitch artwork in Photoshop!

Learn how to create custom UISwitch artwork in Photoshop!

This is a blog post by iOS Tutorial Team member Tope Abayomi, an iOS developer and Founder of App Design Vault, your source for iPhone App Design.

Welcome back to our Photoshop for Developers tutorial series!

In the first part of the series, I showed you how to make a leather-themed Navigation Bar.

Today you will learn how to create a custom leather-themed UISwitch in Photoshop, and get it working in your app!

As you may know, Apple has provided a way to partially customize a UISwitch using the UIAppearance protocol. You’ll go through that first to see how it’s done, then you’ll learn how to take it even further with a helper class.

If you want to take it to the next level and go completely custom, keep reading – this tutorial is for you!

Customizing the UISwitch using the Appearance SDK

You can easily customize a lot of controls in iOS with the UIAppearance system introduced in iOS 5, but right now the options to customize a UISwitch are pretty limited. All you can control is the thumb color and the tint color!

If that’s all you need to do it’s pretty easy – you can do it with just 3 lines of code:

[[UISwitch appearance] setOnTintColor:[UIColor colorWithRed:104.0/255 green:73.0/255 blue:54.0/255 alpha:1.0]];
[[UISwitch appearance] setTintColor:[UIColor colorWithRed:213.0/255 green:183.0/255 blue:165.0/255 alpha:1.000]];
[[UISwitch appearance] setThumbTintColor:[UIColor colorWithRed:125.0/255 green:30.0/255 blue:21.0/255 alpha:1.000]];
 
UISwitch* apSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(72, 60, 63, 23)];
[self.view addSubview:apSwitch];

And you end up with a switch that looks like this:

It doesn’t look bad at all and for some of you, this might be good enough.

But if you want to go hardcore, you will have to use some helper code and fire up Photoshop to get it done. Let get started!

Note: For more information about the UIAppearance system and customizing controls in iOS, check out our User Interface Customization in iOS 6 tutorial.

Customizing USwitch using Photoshop

In the rest of the tutorial, you will learn how to design the UISwitch shown earlier. The colour scheme and design will go hand in hand with the leather theme from the previous tutorial.

First, open up Photoshop and create an new file. Make it 500px by 500px.

Next, change the foreground colour to #e7ddc4.

Fill the background layer with the colour you have just chosen. To to this, click on Edit->Fill and then choose foreground colour.

Now you will create the background of our switch. To do that, select the rounded rectangle tool. If that tool is not currently displayed, hold the mouse down on the tool and it will display options for you – choose the rounded rectangle tool.

Set the Fill colour to anything you want – I used #f9ad81. Remove the stroke by making the width 0px. Set the radius to 22.

Draw a rounded rectangle on the stage. The dimensions should pop up as you drag across the canvas. Make it 125px wide and 44px high. Alternatively, you can click anywhere on the screen and a dialog will pop up that allows you to type in the desired dimensions.

Now you are going to apply some layer style magic to make the background look indented. First, decrease the Fill percent to around 22%. This makes the fill color somewhat transparent while allowing the layer style effects to stay visible.

Double click in the Rounded rectangle layer to bring up the Layer style dialog.

The first layer style you will add is a black inner shadow – this is what makes it look indented! Select the Inner Shadow item on the left and change the settings to what you see below. The colour of the inner shadow is #160a03 – click on the colour box beside the Blend mode to bring up the colour picker, and paste #160a03 into the box at the bottom.

Next, add a black Inner Glow to extend the indented effect. The colour of the Glow is #1a0d04.

Add a Gradient overlay style with the settings shown below.

Lastly, add a white drop shadow. This highlight along the lower edge makes the shape look like it is embedded in the canvas.

All right! The background is looking good!

Now that the background of the switch is complete, you will make the switch handle or thumb image.

Creating the Thumb Image

Choose the rounded rectangle tool and change it to an ellipse tool.

Draw a circle on the canvas. Make it 38px wide and 38 px high. You can hold down the shift-key to keep it a circle as you drag.

Let’s add some layer styles to give the thumb the look of chrome. First, you’ll need to give it a grey-and-white gradient.

I could tell you the values of all the different stops and make you manually change them, but that would be a huge pain! To avoid this, I saved the stops as a gradient file which you can download here.

You can find lots of other great metal gradient files at Photoshopland, like this awesome free one with 110 metal gradients.

Once the file is downloaded, double-click the circle shape layer to bring up the Layer Style dialog. Add a Gradient Overlay. Click on the Gradient bar to bring it up, and load your new gradient by clicking Load, and choosing the file you downloaded.

Make the style of the gradient Angle, and marvel at the lovely chrome. But wait, you’re not finished quite yet!

Add a stroke layer style and change the Fill Type to Gradient. Choose your chrome gradient and set the style as Angle. Make the stroke 2 pixels.

Now you the thumb image is taking on some shape. But it doesn’t look quite connected to the background. You need to add a drop shadow. Use the settings in the image below:

Now you have a nice custom UISwitch. The On/Off text will be added in code later. Let’s slice the images so that you can use it in our Xcode project!

Slicing the images

To export the individual images for the switch background, turn off the visibility of the thumb layer and the background layer.

Choose Image>Trim and make sure “Transparent Pixels” is selected and all the lower boxes are checked. This will trim away everything but our background shape. You can also use the Crop tool to do this.

Export the image as a PNG. To do this, select File->Save As and give it a name like “switchBackground@2x.png”. Make sure to select the PNG option.

You exported the retina version. You can either resize the image (go to Image>Image Size) in Photoshop and re-export the PNG again, or open it in preview, cut the dimension by half and save it as switchBackground.png. Alternatively, you can use one of these image resizers.

Undo the Trim in Photoshop by selecting the Edit->Undo.

Then repeat this process for the thumb image and export it as a PNG. Call the images switchHandle@2x.png and switchHandle.png respectively.

Implementing it in Code

Now you can start writing some code to implement the switch. For this part, you are going to use a modified version of the open source RCSwitch component, which is an implementation of a control just like UISwitch – except you can actually customize the artwork :]

As a starting point, use this Xcode project. I have already added the RCSwitch source to it and from the code below, you will see that I have changed the colour of the background view and added an instance of RCSwitch to the view.

- (void)viewDidLoad
{
 
    [self.view setBackgroundColor:[UIColor colorWithRed:231.0/255 green:221.0/255 blue:196.0/255 
      alpha:1.0]];
 
    RCSwitchOnOff* onSwitch = [[RCSwitchOnOff alloc] initWithFrame:CGRectMake(72, 20, 63, 23)];
    [onSwitch setOn:YES];
    [self.view addSubview:onSwitch];
 
    [super viewDidLoad];
}

Don’t run the code quite yet or it won’t look right – first you have to add the images you exported from Photoshop into the project.

Next open RCSwitch.m, you will see that I have named the images that will be loaded “switchBackground” and “switchHandle” as I suggested above. If you gave them different names, make sure to modify this file and use the name you gave them.

// In setKnobWidth:
UIImage *knobTmpImage = [UIImage imageNamed:@"switchHandle"];
UIImage *knobImageStretch = [knobTmpImage resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
 
// In initCommon
- (void)initCommon
{
    drawHeight = 23;
    /* It seems that the animation length was changed in iOS 4.0 to animate the switch slower. */
    if(kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iOS_4_0){
        animationDuration = 0.25;
    } else {
        animationDuration = 0.175;
    }
 
    self.contentMode = UIViewContentModeRedraw;
    [self setKnobWidth:24];
    [self regenerateImages];
 
    sliderOff = [UIImage imageNamed:@"switchBackground"];
 
    if([[UIScreen mainScreen] respondsToSelector:@selector(scale)])
        scale = [[UIScreen mainScreen] scale];
    else
        scale = 1.0;
    self.opaque = NO;
}

In the initCommon method above, please change the drawHeight value to the height of your swichBackground.png file. If you used the exact dimensions I suggested in the Photoshop file and you cropped it close to the edges, you should end up with a number close to 23.

Now you can run the Xcode project and you should end up with this:

Now that is a custom switch with a chrome handle. You will notice that the On/Off text is kind of out of place. Let’s make that look nice, shall we?

Open RCSwitchOnOff.m and add the following attributes to the labels:

@implementation RCSwitchOnOff
 
- (void)initCommon
{
    [super initCommon];
    onText = [UILabel new];
    onText.text = NSLocalizedString(@"ON", @"Switch localized string");
    onText.textColor = [UIColor whiteColor];
    onText.font = [UIFont boldSystemFontOfSize:14];
    onText.shadowColor = [UIColor colorWithRed:104.0/255 green:73.0/255 blue:54.0/255 alpha:1.0];
    onText.shadowOffset = CGSizeMake(0, 1);
 
    offText = [UILabel new];
    offText.text = NSLocalizedString(@"OFF", @"Switch localized string");
    offText.textColor = [UIColor colorWithRed:104.0/255 green:73.0/255 blue:54.0/255 alpha:1.0];
    offText.font = [UIFont boldSystemFontOfSize:14];
    offText.shadowColor = [UIColor whiteColor];
    offText.shadowOffset = CGSizeMake(0, 1);
}

This adds some colors and shadows to both labels so they look a bit better. Now if you run the app, you should end up with this:

and this for the “Off” text:

That’s it – you just made a custom UISwitch! I hope you like the outcome of your hard work and have learned a bit about Photoshop along the way! :]

Where To Go From Here?

You can download the final project and Photoshop file here.

This tutorial showed you how to create one of the UI elements in the Foody app design template. As you can see, it’s quite a bit of work! :]

If you want to create a good looking template for your app without the hassle, you can get a complete template here that includes custom designs for almost all the UIKit controls including Navigation Bar, Tab Bar, UISwitch, UISegmentedControl, UIButton, UIProgressBar, USlider, iPad and iPhone retina designs, and more.

Again I hope you enjoyed this tutorial, and if you have any questions or comments about this tutorial or creating artwork for iPhone apps in Photoshop in general, please join the forum discussion below!

This is a blog post by iOS Tutorial Team member Tope Abayomi, an iOS developer and Founder of App Design Vault, your source for iPhone App Design.

Tope Abayomi
Tope Abayomi

Tope Abayomi is an iOS developer and Founder of App Design Vault, your source for iPhone App Design. You can find Tope on Twitter.

User Comments

10 Comments

  • Hey nice article. Just a couple Photoshop Shortcuts!

    1.) You can select both of your Switch Handle rounded rectangle layers and right click and say convert to smart object. You can then move that around as if it were one layer.
    2.) You can then Option + Click on the eye (toggle visibility) when you option+click it will hide all other layers.
    3.) You can then put cursor over the preview of layer in layers panel and hold down CMD and click, that will put a marquee around that object in layer
    4.) when you have marquee then just goto IMAGE menu->Crop and you will then be prepared to simply save for web as transparent PNG.

    I did a little screen cast just to show you what I mean. http://screencast.com/t/psIgbVWj0D

    Either way, great article!
    mattpramschufer
  • OMG, This is really a time-saver. Thanks for doing this.

    Ray, can we add this to the tutorial as an update? Readers can slice images faster and more accurate than what is currently in the article.

    mattpramschufer wrote:Hey nice article. Just a couple Photoshop Shortcuts!

    1.) You can select both of your Switch Handle rounded rectangle layers and right click and say convert to smart object. You can then move that around as if it were one layer.
    2.) You can then Option + Click on the eye (toggle visibility) when you option+click it will hide all other layers.
    3.) You can then put cursor over the preview of layer in layers panel and hold down CMD and click, that will put a marquee around that object in layer
    4.) when you have marquee then just goto IMAGE menu->Crop and you will then be prepared to simply save for web as transparent PNG.

    I did a little screen cast just to show you what I mean. http://screencast.com/t/psIgbVWj0D

    Either way, great article!
    Tope Abayomitope
  • Makes a very nice looking switch, would like to see more tutorials like this.
    mmoore410
  • Great its so useful for us. Thank you man :)
    jagaa1103
  • Very well thought out and presented. It might be a little more useful if we were able to do these with vector art, either in Illustrator or a Photoshop vector object since we often need to produce graphics at 2x the size for higher resolution devices.

    As an example, here are some Illustrator comps I did for vector button graphics back in 2008 in Illustrator.

    http://i.imgur.com/P5FZT.png
    http://i.imgur.com/QgAaQ.png
    zav
  • Hi thanks for this second tutorial in designing for developer
    i'm new in designing and i try to get this photo with different text "Romics" and 512*512
    link for photo

    http://www.iconarchive.com/show/mega-ga ... -icon.html

    and any suitable background for image

    i want it to look like for rage comics maker please help me.

    thanks again for your tutorial.
    mohamedkhairy
  • Thanks! Would be great to see some Pixelmator tutorials for UI design. Who can afford Photoshop these days? ;)
    Fadi
  • Fadi wrote:Thanks! Would be great to see some Pixelmator tutorials for UI design. Who can afford Photoshop these days? ;)


    The best thing that Adobe has come out with is the Creative Cloud Service... $49.99 per month and you get the entire creative suite and all updates when they come out. Much more affordable.
    mattpramschufer
  • Great post! Thank you.

    I implemented a control like UISwitch designing a custom CRDScrollSwitch class that you can find at this GitHub repository.

    Since I am a software developer not a graphic designer, I cannot afford Photoshop nor Adobe's Creative Cloud Service.
    So I customized the control appearance by means of the open source GIMP.
    corerd
  • Hi,

    I needed a custom UISwitch with 2 state images (one for "ON" and one for "OFF") but as I couldn't find anything around the web, I've created my own.

    What I came up with is far more simple than your example here and uses 4 views to display the custom switch (one acting as the container, one for the "ON" background, one for the "OFF" background and one for the nob itself which changes it's image depending on its state).

    The switch, including an example can be found on github.
    flavius

Other Items of Interest

Ray's Monthly Newsletter

Sign up to receive a monthly newsletter with my favorite dev links, and receive a free epic-length tutorial as a bonus!

Advertise with Us!

Hang Out With Us!

Every month, we have a free live Tech Talk - come hang out with us!


Coming up in May: Procedural Level Generation in Games with Kim Pedersen.

Sign Up - May

Coming up in June: WWDC Keynote - Podcasters React! with the podcasting team.

Sign Up - June

Vote For Our Next Book!

Help us choose the topic for our next book we write! (Choose up to three topics.)

    Loading ... Loading ...

Our Books

Our Team

Tutorial Team

  • Marcelo Fabri

... 55 total!

Editorial Team

... 22 total!

Code Team

  • Orta Therox

... 1 total!

Translation Team

  • Victor Grushevskiy
  • Jiyeon Seo

... 38 total!

Subject Matter Experts

  • Richard Casey

... 4 total!