std::function在cocos2dx中可以用于界面信息交互,回调
当前有界面ALayer,其中有ASprite以及BLayer为ALayer的Child
BLayer中有控件BButton,当BButton触发时通知ALayer的ASprite切换图片
ALayer.cpp
//首先ALyer内,添加BLayer和ASprite
bool ALyer::init()
{
if ( !Scene::init() )
{
return false;
}
auto visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
m_pLogo = Sprite::create("zuoqi_head_5.png");
m_pLogo->setScale(3);
m_pLogo->setPosition(Vec2(origin.x + visibleSize.width/2,origin.y + visibleSize.height/3*2));// - m_pLogo->getContentSize().height));
this->addChild(m_pLogo);
m_pBLayer = BLayer::create();
this->addChild(m_pBLayer,1);
//这里ALayer定的函数传递给BLayer,达到在BLayer中调用其父节点ALyer的函数
m_pALayer->SetClickCallBack(CC_CALLBACK_0(HelloWorld::ChangeSprite,this));
return true;
}
void ALyer::ChangeSprite()
{
m_pLogo->initWithFile("zuoqi_head_19.png");
}
BLayer.h
class BLayer:public cocos2d::Layer
{
public:
static ALayer* create();
//设置ALayer的监听
typedef std::function<void()> ccCallByHelloword;
void SetClickCallBack(ccCallByHelloword callback)
{
//这里接收ALyer传递的参数
m_callback =callback;
}
private:
bool init();
//点击按钮调用
void ButtonCallback(cocos2d::Ref* pSender);
ccCallByHelloword m_callback;
};
BLayer.cpp
void BLayer::ButtonCallback(Ref* pSender)
{
m_callback();
}