最近在学习cocos2dx需要在场景切换的时候传值这方面的资料貌似很少。大都都有错误.
应用场景是: A->B B->A在B退回A时并传递参数
首先在B头文件定义
std::function<void(int a)> func;
std::function<void(__String * userName, __String * passWord )> funcU;
在 A中声明并实现
void callback1(int a);
void callback2(__String *userName,__String *password);
void LoginLayer::callback1(int a)
{
log("反向传值 %d",a);
}
void LoginLayer::callback2(__String *userName,__String *password){
log("userName = %s \n password = %s ",userName->getCString(),password->getCString());
}
在A->B时 注册回调函数
auto rScene = ResigisterLayer::createScene();
ResigisterLayer *resigisterLayer = dynamic_cast<ResigisterLayer*>(rScene->getChildByTag(1));
IF_NULLPTR_LOG_ASSERT_RETURN(resigisterLayer);
resigisterLayer->func = std::bind(&LoginLayer::callback1,this,std::placeholders::_1 );//绑定回调函数到子场景
resigisterLayer->funcU = std::bind(&LoginLayer::callback2, this,std::placeholders::_1,placeholders::_1);
Director::getInstance()->pushScene(rScene);
在B 场景中调用 场景中调用 func(99); 就相当于调用的主场景的 callback1(99) 了 。 相当于调用的主场景的 callback1(98) 了 。