CCNotificationCenter处理消息事件

define CLICK_TEST_MSG "whatever_unique"   
  
// 添加监听   
void GameMgr::addListener() {  
    CCNotificationCenter* t_pNotiCenter = CCNotificationCenter::sharedNotificationCenter();  
    SEL_CallFuncO t_oCallFuncO = callfuncO_selector(GameMgr::onClickTest);  
    t_pNotiCenter->addObserver(this, t_oCallFuncO, CLICK_TEST_MSG, NULL);  
}  
  
// 派发事件   
void GameMgr::dispatchEvent() {  
    CCNode* t_pNode = new CCNode();  
    CCString* t_pCcStrMsg = new CCString("i love u!");  
    t_pNode->setUserData(t_pCcStrMsg);  
      
    CCNotificationCenter* t_pNotiCenter = CCNotificationCenter::sharedNotificationCenter();  
    t_pNotiCenter->postNotification(CLICK_TEST_MSG, (CCObject*)t_pNode);  
}  
  
// 事件响应   
void GameMgr::onClickTest(CCObject* in_pCcObjData) {  
    CCNode* t_pNode = (CCNode*)in_pCcObjData;  
    CCString* t_pCcStrMsg = (CCString*)t_pNode->getUserData();  
    CCMessageBox(t_pCcStrMsg->getCString(), "Message");  
      
    // 传递完毕不要忘记释放内存   
    t_pCcStrMsg->release();  
    t_pNode->release();  
}  
  
// 移除监听   
void GameMgr::removeListener() {  
    CCNotificationCenter* t_pNotiCenter = CCNotificationCenter::sharedNotificationCenter();  
    t_pNotiCenter->removeObserver(this, CLICK_TEST_MSG);  
}  


 

然后写个小程序来实践下这个。

改用系统为我们创建的Helloworld,首先将系统中建立退出按钮的代码注释掉。

然后Helloworld::init中末尾这样写

 

		CCSprite *button = CCSprite::create("CloseNormal.png");
		button->setPosition(ccp(200,300));
		CCNode* t_pNode = new CCNode();  
     
		t_pNode->setUserData(button);

		CCNotificationCenter* t_pNotiCenter = CCNotificationCenter::sharedNotificationCenter(); 
		t_pNotiCenter->addObserver(this, callfuncO_selector(HelloWorld::onClickTest), CLICK_TEST_MSG, NULL);


		CCNotificationCenter::sharedNotificationCenter()->postNotification(CLICK_TEST_MSG, (CCObject*)t_pNode);
	
	
		this->addChild(button);


最后添加响应函数

void HelloWorld::onClickTest(CCObject* obj)
{
	CCNode *temp =(CCNode*)obj;
	CCSprite *button =(CCSprite*)temp->getUserData();
	button->setPosition(ccp(100,100));

}


 

最后看运行截图,看看按钮的位置。 证明事件真的被执行了。成功

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值