.h文件
bool HelloWorld::init()
{
//////////////////////////////
// 1. super init first
if ( !CCLayer::init() )
{
return false;
}
CCLabelTTF * label = CCLabelTTF::create("爲選中文字", "MarkerFelt",25);
CCControlButton * button = CCControlButton ::create(label,CCScale9Sprite::create("button.png"));
button->setPosition(ccp(240, 170));
// 按鈕選中後背景圖響應的狀態
button->setTitleColorForState(ccc3(255, 0, 0), CCControlStateHighlighted);
// 按鈕選中後文字響應的狀態
button->setTitleForState(CCString::create("選中文字"), CCControlStateHighlighted);
addChild(button);
// 按下按鈕事件回調
button->addTargetWithActionForControlEvents(this, cccontrol_selector(HelloWorld::touchDownAction), CCControlEventTouchDown);
// 按鈕在其內部拾起事件回調
button->addTargetWithActionForControlEvents(this
, cccontrol_selector( HelloWorld::touchUpInsideAction), CCControlEventTouchDragEnter);
// 按鈕在其外部拾起事件回調
button->addTargetWithActionForControlEvents(this,cccontrol_selector(HelloWorld::touchUpOutsideAction), CCControlEventTouchDragOutside);
// 用於顯示按鈕的狀態
CCLabelTTF * la = CCLabelTTF ::create(" ", "MarkerFelt",20);
la->setColor(ccc3(255, 0, 0));
la->setPosition(ccp(240, 220));
addChild(la,0,923);
return true;
}
// 按下按鈕事件回調
void HelloWorld:: touchDownAction(CCObject * sender , CCControlEvent * controlEvent)
{
CCLabelTTF * label = (CCLabelTTF*) this ->getChildByTag(923);
label->setString(CCString::createWithFormat("按下")->getCString());
}
// 按鈕在其內部擡起事件回調
void HelloWorld::touchUpInsideAction(CCObject * sender , CCControlEvent * controlEvent)
{
CCLabelTTF * label = (CCLabelTTF*) this ->getChildByTag(923);
label->setString(CCString::createWithFormat("內部擡起")->getCString());
}
// 按鈕在其外部擡起事件回調
void HelloWorld::touchUpOutsideAction(CCObject * sender , CCControlEvent * controlEvent)
{
CCLabelTTF * label = (CCLabelTTF*) this ->getChildByTag(923);
label->setString(CCString::createWithFormat("外部擡起")->getCString());
}
.cpp文件
#include "cocos2d.h"
#include "cocos-ext.h"
using namespace cocos2d;
using namespace extension;
class HelloWorld : public cocos2d::CCLayer
{
public:
// Method 'init' in cocos2d-x returns bool, instead of 'id' in cocos2d-iphone (an object pointer)
virtual bool init();
// there's no 'id' in cpp, so we recommend to return the class instance pointer
static cocos2d::CCScene* scene();
// a selector callback
void menuCloseCallback(CCObject* pSender);
// preprocessor macro for "static create()" constructor ( node() deprecated )
CREATE_FUNC(HelloWorld);
// 按下按鈕事件回調
void touchDownAction(CCObject * sender , CCControlEvent * controlEvent);
// 按鈕在其內部拾起事件回調
void touchUpInsideAction(CCObject * sender , CCControlEvent * controlEvent);
// 按鈕在其外部拾起事件回調
void touchUpOutsideAction(CCObject * sender , CCControlEvent * controlEvent);
};