cocos2dx观察者模式

匿名 (未验证) 提交于 2019-12-03 00:22:01

开始

第一次运行


#ifndef EventListenerCustomTest_hpp

#define EventListenerCustomTest_hpp


#include <stdio.h>

#include "cocos2d.h"

USING_NS_CC;

#include "cocostudio/CocoStudio.h"

#include "ui/CocosGUI.h"

using namespace cocos2d::ui;

class EventCustomTest :public Layer {

public:

static Scene* createScene();

bool init();

CREATE_FUNC(EventCustomTest);

Text* statusLabel;

};






#endif /* EventListenerCustomTest_hpp */


//

//

//

//


#include "EventListenerCustomTest.hpp"

Scene* EventCustomTest::createScene()

{

auto scene = Scene::create();

auto layer = EventCustomTest::create();

addChild(layer);

return

}

bool EventCustomTest::init()

{

if (!Layer::init()) {

return false;

auto btn = Button::create();

setTitleText("Start");

setTitleColor(Color3B::YELLOW);

setTitleFontSize(25);

setPosition(Vec2(240, 160));

this->addChild(btn);

static int count = 0;

addClickEventListener([=](Ref* sender){

char* buf = new char[10];

sprintf(buf, "%d", count);

EventCustom event("event1");

setUserData(buf);

//发送用户数据

_eventDispatcher->dispatchEvent(&event);

CC_SAFE_DELETE_ARRAY(buf);

statusLabel = Text::create();

statusLabel->setString("test");

statusLabel->setPosition(Vec2(160, 230));

statusLabel->setColor(Color3B::YELLOW);

statusLabel->setFontSize(30);

this->addChild(statusLabel);

//cocos2dx观察者模式EventListenerCustom的使用(代替NotificationCenter

创建一个监听事件,第一个参数是事件的键值名(事件名)

auto _listener = EventListenerCustom::create("event1", [=](EventCustom* event)

std::string str("event 1 received, ");

//接受char* 类型用户数据

char* buf = static_cast<char*>(event->getUserData());

" times";

statusLabel->setString(str.c_str());

Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(_listener, this);

return true;

}





易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!