# Create an iPhone Inspired Switch CheckBox Using Flash and ActionScript 3.0

A CheckBox is a graphical user interface element that permits the user to make one or multiple selections from a number of options.

In this tutorial, we’ll create a Switch checkbox inspired by the iPhone Graphical User Interface. Read on to find out how!

## Step 1: Brief Overview

Using the Flash drawing tools we’ll create a vector Switch that will be controled by classes. One class will take care of all the Switch behavior and another class will simply check the value of the Switch. Let’s go!

## Step 2: Starting

Open Flash and create a new Flash File (ActionScript 3).

Set the stage size to 600×300 and set the color to #EFEFF0.

We’ll now create the Switch graphics.

## Step 3: Border

Select the Primitive Rectangle Tool (R) and create a 280×80 px rectangle, filling it with this linear gradient: #505052, #ACADB1.

Use the Gradient Transform Tool to rotate the gradient horizontally and change the corner radius (Properties Panel) to 10.

## Step 4: OFF Background

We’ll draw two backgrounds for the Switch, the OFF background and the ON background.

Duplicate the previous shape and change its size to 276×76 px. Change the linear grandient to #9A9A9A, #F4F3F6 and move the last color selector (Color Panel) to halfway along the bar.

Select the Text Tool (T) and create a Static TextField. Write "OFF" and place it at the right side of the background.

I used Helvetica Neue Bold, 48 pt, #8C8C8C.

## Step 5: Draggable Area

Now we’ll add a button that can be dragged to modify the Switch value.

Use the Rectangle Tool to create a 120×80 px rectangle and fill it with #A19FA0, set the corner radius to 10.

Duplicate the shape and resize it to 116×76 px, fill it with #FCFCFE.

To give the final touch to the button, repeat the process and fill the shape with a #D7D7D7, #FCFCFE linear gradient. Use the Gradient Transform Tool to rotate the fill.

## Step 6: ON Background

Duplicate the border and the OFF background, delete the text and change the border gradient to #0D4372, #6193D2.

Next, change the background gradient to #0C68B5, #479FF9, #6DB0F6.

Place the button border shape in the right side.

Break Apart (Cmd+B) the shapes to cut them.

Use the same Text Format to add the "ON" text to the background.

## Step 7: Setting the MovieClips

Convert the Draggable Button to MovieClip and name it "area". As you can imagine this will be the area that will be dragged to change the Switch value.

Make sure the Registration point is positioned like the one in the images.

Select all shapes including the MovieClip and convert them again, name the result "slider".

Use any of the border shapes to create another MovieClip, this will be the Mask that will hide part of the graphics. Name it "msk".

Convert everything to MovieClip once again and double-click it.

Create a new Layer then cut and paste the mask clip on it. Right-click the mask layer and select the "Mask" option.

This will finish all the graphics. Now your Switch should look like this (note the Registration point):

Open the Library and right-click your Switch symbol. Select Properties, mark the "Export for ActionScript" box and write "Switch" as the class name.

## Step 9: Switch.as

Create a new ActionScript document and save it as "Switch.as".

## Step 10: Necessary Classes

Import the required classes. If you need specific help for any of these, please refer to the Flash Help (F1).

package
{
import fl.transitions.Tween;
import fl.transitions.easing.Strong;
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.geom.Rectangle;

## Step 11: Variables

These are the variables we’ll use, explained in the code commentary.

public class Switch extends Sprite
{
private var tween:Tween; //A Tween object for animation
public var stat:Boolean = false; // This is a Public variable, it's used to know the Switch value outside this class

## Step 12: Constructor Function

The Constructor function. This function adds the listeners.

public function Switch():void
{
}

## Step 13: Drag function

This function handles the button dragging, based on its position.

private function switchDrag(e:MouseEvent):void
{
if (! stat) //If Switch is OFF, we can drag to the right
{
e.target.parent.startDrag(true, new Rectangle(0, 0, e.target.parent.parent.msk.width/1.75, 0));
}
else
{
e.target.parent.startDrag(true, new Rectangle(e.target.parent.parent.msk.width/1.75, 0, -e.target.parent.parent.msk.width/1.75, 0));
}
}

## Step 14: Check Function

This code checks the position of the draggable button. Depending on its value it returns to the original position or stays in the new one.

private function checkPosition(e:MouseEvent):void
{
e.target.parent.stopDrag();

if (e.target.parent.x >= 140)
{
e.target.parent.x = 160;
stat = true;
}
else if (!stat && e.target.parent.x < 140)
{
tween = new Tween(e.target.parent,"x",Strong.easeOut,e.target.parent.x,0,1,true);
stat = false;
}

// OFF to ON

if (e.target.parent.x <= 20)
{
e.target.parent.x = 0;
stat = false;
}
else if (stat && e.target.parent.x > 20)
{
tween = new Tween(e.target.parent,"x",Strong.easeOut,e.target.parent.x,160,1,true);
stat = true;
}
}

## Step 15: Main Class

This is an example of how to use your new Switch.

Create a new ActionScript document and save it as "Main.as".

package
{
import Switch; //Import the class
import flash.display.Sprite;
import flash.events.MouseEvent;

public class Main extends Sprite
{
public function Main():void
{
iSwitch.addEventListener(MouseEvent.MOUSE_UP, checkState);//iSwitch is an instance in the stage of the Switch class
}

private function checkState(e:MouseEvent):void
{
if(iSwitch.stat)
{
trace("Switch is ON!");
}
else
{
trace("Switch is OFF!");
}
}
}
}

## Step 16: Document Class

Go back to the .Fla file and in the Properties Panel add "Main" in the Class field to make this the Document Class.

## Conclusion

You have created a fully customizable Switch to use in your applications! Remember that you can create your own skins and add plenty more functionality to the ON and OFF states.

• d3rson

very nice….

• flora

Thanks ;)

• http://www.juxt2.com Dimitree

Sweet!!! Very well designed

• André

Amazing

thanks

• Alexander

Something very buggy….

• vasu

Hi, i like this tut. i want touch scroll like iphone type. like click and throw. can u upload it?

• André

wow, i´ve made something like this, but my tutorial you drag and throw a ball, but i´ve adapted to a scroll… the result of the tutorial is here:

http://cavallari.freehostia.com/testswf/?swf=DragAndThrow.swf

But as it have too few steps, yan asked me to add more, but as i am in last year of my great college now i am a little bit off time, but when i have time i will remake the tutorial and resend to yan, also, as you asked, i will send how to use this with a scrooll.

• vasu

nice that. but i need tutorial please.

• http://republik9.com Erick

And you got this from AS3 Animation by Keith Peters

• viaria

it is cool but there is no gravity,

• André

Yeah, there is no gravity because it´s not a real ball, it´s for a pong game or a throw slider, but gravity is the less complicated thing, this is an extendable object, but nice observation, when i finish the tutorial i will add gravity functionality too.

“And you got this from AS3 Animation by Keith Peters”
No, i didnt, i already sent this tutorial to Yan, he just asked to have more steps, so i will add some functionalities to have more steps, it doesnt use any kind of Tween engine.

• Ryan

Check out Lee Brimelows tutorial on creating a throw slider, it might be what you’re looking for.

gotoandlearn.com

• http://hanusek.com John Hanusek

Very nice. I just made something very similar to this using the iPhone toggle switch as inspiration. It’s more of a horizontal slider but translates very well.

http://www.dwskatesurf.com/skate-shop/completes.html

• http://www.wpsmash.com WPSMASH

Thank you for this great tutorial!

• Dolores

thank you very much:–))

• Bun

I would suggest to add some basic physics to throw the slider like lee brimelow’s one in http://gotoandlearn.com/play?id=81 tutorial. To me personaly is annoying that you have to push the slider to the end. Other possible thing to to is to add simple ? : statement, if when you stop drag the slider it is more of parent width-hes width/2 to switch it, else to return

• Xtian

The final output is buggy

• Karl Macklin

Agreed – when flipped to the right, and you just single click on the button, it flies all over.

Other than the design of the button, the tutorial kind of loses it’s worth if you don’t iron out all these kinks. Try using the iPhone’s toggle button as inspiration – not only for the design, but also the behaviour of it.

• Asim

Great tutorial !!! I like it .. but do u know about ADOBE CATALYST
u can do do simmiar thing in just clicks but that won’t work like AS3.0
thanx…

• http://labs.dariux.com Dario Gutierrez

Looks very easy.

• Deoxys

Not really original ;-)

• http://www.teskostudio.com Roberto

I don´t see the point of using OOP here.

It is important to know how OOP works but it makes sense only when you take really profit of encapsulation and when it worths the time you have to spend creating classes. This can be done in half of the time using just frame coding. There´s nothing wrong about that.

I can understand that a the tutorial is made for demonstration purposes but it is always good to remember that OPP is not a religion, just a very handy tool we can take benefit from. That should be considered as a good practice when working with AS3 as well.

Anyway, thanks for the tutorial :)

Cheers.

• http://www.richardlayte.com Rich

It might be quicker the first time, but what if you need to use this in a second project, or have multiple instances within the same project?

The timeline is still an excellent tool for animation, but shouldn’t be used to define interactivity.

• André

Yeah, i agree.

There are sometimes that you think: “the project is too small, i will use timeline”, them the project extends, and becomes bigger and bigger, so the timeline becomes a mess, and you cant use your codes for other projects

• Travis Estep

The demo that is included with this tutorial is really buggy. The animation seems to have some problems. I even tried it on 3 different computers, one with XP, one with Vista and one with Windows 7. I haven’t had a chance to look at the code yet to see what the problem is, but are you open for suggestions if I can pinpoint the problem? I’d be more than happy to help out so that the less knowledgeable users can replicate this without any problems.

• jack

The only thing thats “buggy” about it is that the tween needs to be removed when the user clicks on the tab again. For example, when you switch it over to “on,” and let go, it starts to tween to 0.0 or whatever the value is. If you try to drag it before it hits 0.0 and the duration of the tween, then it keeps trying to tween to 0.0. Make sense?

• http://www.sevenderd.com sevenderd

good input

• anomynous

Nice tut except the animation is very buggy. Moving the slider to the right goes smoother than to the left. When going to the left it has a tendency to not stay set unless you get it in just the right position. Also there is no animation when moving it to the left and it keeps flashing back to the right while the mouse is still held down. I’m losing my faith in flash as a cross-browser plugin. It no-longer provides that seamless transition across all OS/browser combination’s.

• http://www.almogdesign.net Almog Koren

You have a bug, “common mistakes with drag in AS3″ You also need physics to make it like the iPhone.

function stopDrag(event:MouseEvent):void {

stopDrag();

}

• http://spotdex.com David Moreen

The UI is extraordinary, but the demo is buggy as hell.

• http://www.englar-design.com Englar
• John

Yeah unfortunately it is very buggy. Also – when you momentarily press and release a switch on the iPhone – it automoatically moves to the other position.

• http://www.thibautgrevet.fr Thibaut

Hey, thank you very much for the slider.
However I try to make a Url request when slider is on and i can’t find a solution.
Someone can help me ….

Thanks
thibaut

• http://alexey-gara.ru Alexey

why are you using MouseEvent, not TouchEvent

• Pingback: iOS Welchen Tweener? - Flashforum