A switch in the Switchcontrol control class plays a role like switching in real life
Because of the relatively simple control, I did not do too much explanation. Directly in the code
First, add three images to the resource folder under the project folder
Add the following code to SwitchControl.h
#ifndef _switchcontrol_h_#define _switchcontrol_h_#include "cocos2d.h" #include "cocos-ext.h" USING_NS_CC; Using_ns_cc_ext;class switchcontrol:public cclayer {public: static ccscene* scene (); Create_func (Switchcontrol); bool Init (); void Switchvaluechanged (ccobject*, cccontrolevent);}; #endif
Add the following code to the SwitchControl.cpp
#include "SwitchControl.h" ccscene* Switchcontrol::scene () {ccscene* s = ccscene::create (); switchcontrol* layer = Switchcontrol::create (); S->addchild (layer); return s;} BOOL Switchcontrol::init () {cclayer::init (); Get the size of the form ccsize winsize = Ccdirector::shareddirector ()->getwinsize (); Set Controlswitch control to open Text No "cclabelttf* on = Cclabelttf::create (" On "," Arial ", 16); Sets the text "off" when the Controlswitch control closes cclabelttf* off = cclabelttf::create ("Off", "Arial", 16); Sets the color of text opened by the Controlswitch control On->setcolor (CCC3 (0, 0, 0)); Sets the color off->setcolor when the Controlswitch control is turned off (ccc3 (0, 0, 0)); Create Controlswitch controls cccontrolswitch* control = Cccontrolswitch::create (Ccsprite::create ("Switch-mask.png"), CCSp Rite::create ("Switch-on.png"), Ccsprite::create ("Switch-off.png"), Ccsprite::create ("Switch-thumb.png"), ON, O FF); Add Controlswitch control addChild; Sets the position of the Controlswitch control Control->setposition (CCP (Winsize.width/2, WINSIZE.HEIGHT/2));//register Valuechange message when Valuechange. Call the Switchvaluechanged function control->addtargetwithactionforcontrolevents (this, Cccontrol_selector (SwitchControl:: switchvaluechanged), cccontroleventvaluechanged); return true;} void Switchcontrol::switchvaluechanged (ccobject* sender, cccontrolevent ev) {if (ev = = cccontroleventvaluechanged) { cccontrolswitch* control = (cccontrolswitch*) sender;if (Control->ison ()) {Cclog ("Switch if On");} Else{cclog ("Swith is Off");}} Else{cclog ("other events");}}
Operation Result:
Demo Effect:
Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.
Cocos2d-x used in Switchcontrol