按钮事件
ButtonTestLayer.h
#ifndef _BUTTON_TEST_LAYER_H_
#define _BUTTON_TEST_LAYER_H_
#include "cocos2d.h"
#include "ui\CocosGUI.h" //引入 CocosGui
USING_NS_CC;
class ButtonTestLayer : public cocos2d::Layer
{
public:
static cocos2d::Scene* createScene();
CREATE_FUNC(ButtonTestLayer);
virtual bool init();
//button点击事件
void btnClickCallback(cocos2d::Ref * pSpender);
//button触摸事件
void btnTouchCallback(cocos2d::Ref * sender,cocos2d::ui::Widget::TouchEventType type );
private:
cocos2d::ui::Button * m_pBtn = nullptr;
};
#endif
#include "ButtonTestLayer.h"
using namespace cocos2d::ui; //引入 cocos2d ui
Scene* ButtonTestLayer::createScene()
{
auto scene = Scene::create();
auto layer = ButtonTestLayer::create();
scene->addChild(layer);
return scene;
}
bool ButtonTestLayer::init()
{
Layer::init();
auto visibleSize = Director::getInstance()->getVisibleSize();
float x = 0;
float y = 0;
x = visibleSize.width / 2;
y = visibleSize.height / 2;
m_pBtn = Button::create("CloseNormal.png","CloseSelected.png"); //创建button,两个图片实现一个是平常状态,另外一个是点击时候的状态
//若此处只输入一个图片文件,会自动生成一个动画。
this->addChild(m_pBtn);
m_pBtn->setPosition(Vec2(x, y));//设置button的位置
m_pBtn->addClickEventListener(CC_CALLBACK_1(ButtonTestLayer::btnClickCallback,this));
m_pBtn->addTouchEventListener(CC_CALLBACK_2(ButtonTestLayer::btnTouchCallback, this));
//button回调函数
return true;
}
//ButtonTestLayer::btnClickCallback方法
void ButtonTestLayer::btnClickCallback(cocos2d::Ref * pSpender)
{
Node * pNode = dynamic_cast<Node*>(pSpender);
log("Button click");
}
//ButtonTestLayer::btnTouchCallback方法
void ButtonTestLayer::btnTouchCallback(cocos2d::Ref * sender, cocos2d::ui::Widget::TouchEventType type)
{
if (type == Widget::TouchEventType::BEGAN)
{
log("began");
}
if (type == Widget::TouchEventType::MOVED)
{
log("moved");
}
if (type == Widget::TouchEventType::ENDED)
{
log("ended");
}
//在点击button即可调用 BRGAN,之后移动即可调用MOVED,最后必须移动回按钮,才能调用 ENDED方法
}