我导入了一个cocostudio制作的UI,里面包含了一个按钮,我使用getChildByName函数获得了控件,它是一个NODE类型的指针,我怎么帮它单独添加一个事件呢?helloWorld中的例子是使用MenuItemImage来添加的,我在网上查找到的资料都是如何添加一个触摸事件,总不可能是添加一个触摸事件然后在回调函数中判断坐标然后确定哪个键吧?
对了,我使用的版本是3.2
你的Studio版本是1.x吗?
语言是C++?
getChildByName获取的Node需要你自己转换成对应的类型:
auto your_button = dynamic_cast<button*>(your_node);
widget(button的父类)类型都带有一个addTouchEventListener的函数来添加对触摸事件的回调。
会自动判断有没有按到你的按钮。用这个来设置回调。
哥们谢谢了~但是你说的这个方法貌似已经废弃了,现在都已经没有button这个类了。。 :(
例子:
auto myListener = EventListenerTouchOneByOne::create();
myListener->setSwallowTouches(true);
auto hostRec = Rect(posInGL.x - 0.5 * size.width, posInGL.y - 0.5 * size.height, size.width, size.height);
myListener->onTouchBegan = =](Touch* touch,Event* event)
{
auto target = static_cast<Sprite*>(event->getCurrentTarget());
auto posInGL = Director::getInstance()->convertToGL(target->getPosition());
Point locationInGL = Director::getInstance()->convertToGL(touch->getLocation());
Size s = target->getContentSize();
Rect rect = Rect(posInGL.x - 0.5 * s.width, posInGL.y - 0.5 * s.height, s.width, s.height);
if (hostRec.containsPoint(locationInGL)) {
log("Point the hostcity");
}
if (rect.containsPoint(locationInGL))
{
target->setOpacity(180);
return true;
}
return false;
};
myListener->onTouchMoved = =](Touch* touch,Event* event)
{
auto target = static_cast<Sprite*>(event->getCurrentTarget());
target->setPosition(target->getPosition()+touch->getDelta());
};
myListener->onTouchEnded = =](Touch* touch,Event* event)
{
auto target = static_cast<Sprite*>(event->getCurrentTarget());
if(target)
{
target->setOpacity(255);
}
};
_eventDispatcher->addEventListenerWithSceneGraphPriority(myListener,bgLayout);
没有废弃。3.3上都能用
按钮的第一个字母是大写的,位于命名空间ui中:
ui::Button