最新文章
widget不会自动屏蔽下层触摸
02-25 14:51
widget不会自动屏蔽下层触摸
2015年02月25日 14:51
0 点赞
0 评论
更新于 2025-11-21 16:24
在 Cocos2d-x 3.0 版本中,通常使用 setTouchEnabled(bool enable) 方法来注册触摸优先级。然而,Widget 存在一个问题,即它不会自动屏蔽下层的触摸事件。为了解决这个问题,我们可以通过动态设置 Widget 的触摸优先级,从而方便地屏蔽下方界面的触摸事件。下面将详细介绍具体的实现方法。
代码实现
我们需要在 Widget.h 和 Widget.cpp 文件中添加一个新的方法 setTouchPriority(int priority),以下是该方法的具体代码:
void Widget::setTouchPriority(int priority)
{
// 设置当前 Widget 的触摸优先级
_touchPriority = priority;
// 递归设置子 Widget 的触摸优先级
for (auto& child : _children)
{
if (child)
{
Widget* widgetChild = dynamic_cast<Widget*>(child);
if (widgetChild)
{
// 子 Widget 的触摸优先级比父 Widget 低 1
widgetChild->setTouchPriority(this->getTouchPriority() - 1);
}
}
}
// 如果触摸未启用,则直接返回
if (!_touchEnabled)
return;
// 移除之前的触摸监听器
_eventDispatcher->removeEventListener(_touchListener);
CC_SAFE_RELEASE_NULL(_touchListener);
// 创建新的单点触摸监听器
_touchListener = EventListenerTouchOneByOne::create();
CC_SAFE_RETAIN(_touchListener);
// 设置触摸事件吞噬,即屏蔽下层触摸
_touchListener->setSwallowTouches(true);
// 绑定触摸事件回调函数
_touchListener->onTouchBegan = CC_CALLBACK_2(Widget::onTouchBegan, this);
_touchListener->onTouchMoved = CC_CALLBACK_2(Widget::onTouchMoved, this);
_touchListener->onTouchEnded = CC_CALLBACK_2(Widget::onTouchEnded, this);
_touchListener->onTouchCancelled = CC_CALLBACK_2(Widget::onTouchCancelled, this);
// 添加新的触摸监听器,并设置固定的触摸优先级
_eventDispatcher->addEventListenerWithFixedPriority(_touchListener, _touchPriority);
}
使用注意事项
在使用 setTouchPriority 方法之前,必须确保已经开启了触摸事件,即调用过 setTouchEnabled(true) 方法。这样才能保证触摸事件能够正常处理,并且通过设置触摸优先级来屏蔽下层的触摸事件。
通过以上的方法,我们可以方便地动态设置 Widget 的触摸优先级,从而解决 Widget 不会自动屏蔽下层触摸事件的问题。