- #include "editor-support/cocostudio/CCSGUIReader.h"
- #include "cocostudio/CocoStudio.h"
- #include "ui/CocosGUI.h"
- using namespace cocos2d::ui;
- using namespace cocostudio;
上面就是比较完整的使用UI所需要用到的头文件了。
然后,获取UI控件的方法如下,继续修改createOprUI函数:
- void TollgateScene::createOprUI()
- {
- auto UI = cocostudio::GUIReader::getInstance()->widgetFromJsonFile("OprUI_1.ExportJson");
- this->addChild(UI);
- /* 获取按钮对象 */
- Button* rightBtn = (Button*)Helper::seekWidgetByName(UI, "rightBtn");
- Button* quickMoveBtn = (Button*)Helper::seekWidgetByName(UI, "quickMoveBtn");
- Button* leftBtn = (Button*)Helper::seekWidgetByName(UI, "leftBtn");
- }
Helper::seekWidgetByName函数会从UI里面找控件,一层层的找,父控件找不到,就找子控件,如此递归,最后找的名字相符的控件,返回这个控件对象。
很简单,不多解释喇~
添加按钮回调事件
OK,最后一步了,现在按钮摆在那里什么都做不了,我们给按钮添加回调事件~
先给TollgateScene添加三个函数声明:
- void moveToLeft(Ref* sender, TouchEventType type);
- void moveToRight(Ref* sender, TouchEventType type);
- void quickMove(Ref* sender, TouchEventType type);
这是Button点击事件回调时所需要的函数格式。
然后,继续修改createOprUI函数:
- void TollgateScene::createOprUI()
- {
- auto UI = cocostudio::GUIReader::getInstance()->widgetFromJsonFile("OprUI_1.ExportJson");
- this->addChild(UI);
- /* 获取按钮对象 */
- Button* rightBtn = (Button*)Helper::seekWidgetByName(UI, "rightBtn");
- Button* quickMoveBtn = (Button*)Helper::seekWidgetByName(UI, "quickMoveBtn");
- Button* leftBtn = (Button*)Helper::seekWidgetByName(UI, "leftBtn");
- /* 添加按钮回调事件 */
- leftBtn->addTouchEventListener(this, toucheventselector(TollgateScene::moveToLeft));
- rightBtn->addTouchEventListener(this, toucheventselector(TollgateScene::moveToRight));
- quickMoveBtn->addTouchEventListener(this, toucheventselector(TollgateScene::moveToRight));
- }
利用addTouchEventListener函数就可以绑定按钮的回调事件了~
最后了,看看三个回调函数的实现:
- void TollgateScene::moveToLeft(Ref* sender, TouchEventType type)
- {
- switch (type)
- {
- case TOUCH_EVENT_ENDED:
- m_player->moveToLeft();
- break;
- }
- }
- void TollgateScene::moveToRight(Ref* sender, TouchEventType type)
- {
- switch (type)
- {
- case TOUCH_EVENT_ENDED:
- m_player->moveToRight();
- break;
- }
- }
- void TollgateScene::quickMove(Ref* sender, TouchEventType type)
- {
- switch (type)
- {
- case TOUCH_EVENT_ENDED:
- m_player->quickMove();
- break;
- }
- }