How to set callback on button?

How to set callback on button?
0.0 0


I have started to use CocoStudio. My actions were:

  1. create a UI project
  2. put some elements on scene and name them
  3. export project
  4. create a scene project
  5. add a component “UI” on scene, bind it with exported UI output
  6. Export scene project
    Now I have a .json project output file and resources. In the code I have in extensions the SceneReader. SceneReader can take json file and make CCNode from it.
    But how assign a callback to button on that scene? Should I take it by tag, cast to some button class and set then callback, or there is more convenient path?


I have found some kind of solution:

void MyScene::onClick(CCObject*, TouchEventType aType)
    CCLOG("In touch! %d", aType);

bool MyScene::init()
        return false;
    CCNode* root;
    SceneReader* sceneReader = SceneReader::sharedSceneReader();
    root = sceneReader->createNodeWithSceneFile("NewProject.json");
    if(root == NULL)
        return false;

    UILayer* layer = dynamic_cast(((CCNode*)root->getChildren()->objectAtIndex(0))->getComponent("GUIComponent")->getNode());

          auto button = layer->getWidgetByName("CCLayer")->getChildByName("exit")->getChildByName("CCMenuItemImage");
          button->addTouchEventListener(this, (SEL_TouchEvent)&MyScene::onClick);
    return true;

But the way I get the effect is awful. I hope that it is much more convenient way to bind CocoStudio project with cocos2d-x and set callback on a button.


yep, addTouchEventListener can do what you want


Is the way I have get the element (button) correct? 7 child gets and 2 casts for one button?


musicEffectSlider = dynamic_cast<UISlider*>(this->getWidgetByName(“musicEffect”));
musicVolumeSlider = dynamic_cast<UISlider*>(this->getWidgetByName(“musicVolume”));
UIButton* backGameBtn = dynamic_cast<UIButton*>(this->getWidgetByName(“backGame”));

Try this way. See more in the testCpp about CocoStudio UI Test


Yes, I have seen that. But It needs to be UILayer to use getWidget.

The info that I want to know: should I use UI editor for making my game scenes, or I should use scene editor?
UI editor give me the json file, that I can read with CCSGUIReader and output is UIWidget.
Scene editor give me json file, that I can read with CCSSceneReader, and output is CCNode.

If I want to set callbacks and other functional, should I use UI editor instead of scene editor?


How about use UI editor make game layers, and group them to game scene?


@Oskard: Did you find a better solution to add the callback to a button, which is in a Scene or Widget from CocosStudio?

@zijian.rao: I do not have a getWidgetByName Method.
I am using cocos2d-x-3.1


Is there a way to set not a class method as a callback for the button but a lambda function?


now the latests version did support a lambda function.