Pages

Wednesday, October 17, 2012

AS3: Sliding Toggle Switch like iPhone


The movieclip format would be like this:
<movieclip name="controller_mc" width="200">
 <frameset>
  <frame name="left">
   <movieclip name="slider_mc" x="0" width="100"></movieclip>
   <graphics framespan="2">
    <textfield name="caption1">ON</textfield>
    <textfield name="caption2">OFF</textfield>
   </graphics>
  </frame>
  <frame name="right">
   <movieclip name="slider_mc" x="100" width="100"></movieclip>
  </frame>
 </frameset>
</movieclip>
The source code of the class is given below:
package engine.ui 
{
 import flash.display.MovieClip;
 import flash.events.MouseEvent;
 /**
  * ...
  * @author Abhishek Kumar
  */
 public class CToggleSwitch 
 {
  private var Container:MovieClip;
  private var proceed:Function;
  
  private var toggle:int;
  
  public function CToggleSwitch(mc:MovieClip) 
  {
   Container = mc;
  }
  
  public function initiate():void
  {
   Container.buttonMode = true;
   Container.mouseChildren = false;
   
   toggle = 1;
   toggleState(toggle);
  }
  
  public function setLabels(list:Array):void
  {
   Container.caption1.text = list[0];
   Container.caption2.text = list[1];
  }
  
  public function attachListeners(callback:Function):void
  {
   proceed = callback;
   Container.addEventListener(MouseEvent.CLICK, onClick);
  }
  
  public function detachListeners():void
  {
   Container.removeEventListener(MouseEvent.CLICK, onClick);
  }
  
  private function onClick(me:MouseEvent):void
  {
   toggle = (toggle == 1)?2:1;
   toggleState(toggle);   
   
   proceed(toggle);
  }
  
  private function toggleState(state:int):void
  {
   switch (state)
   {
    case 1: Container.gotoAndStop('right');
     break;
    case 2: Container.gotoAndStop('left');
     break;
   }
  }
  
 }

}

No comments:

Post a Comment