Cocos2d-x ScrollView

解决ScrollView中添加ControlButton后的拖动冲突问题:

自定义类ControlButtonX继承了ControlButton,把要添加到ScrollView中的ControlButton实例修改为ControlButtonX的实例即可。下面贴出ControlButtonX类的.h和.cpp文件源码:

//
//  ControlButtonX.h
//

#ifndef __ControlButtonX__
#define __ControlButtonX__

#include <iostream>
#include "cocos2d.h"
#include "cocos-ext.h"

USING_NS_CC;
USING_NS_CC_EXT;

class ControlButtonX : public ControlButton
{
public:
    ControlButtonX();
    static ControlButton* create(Scale9Sprite* sprite);

public://from
    bool onTouchBegan(Touch *pTouch, Event *pEvent);
    void onTouchMoved(Touch *pTouch, Event *pEvent);
    void onTouchEnded(Touch *pTouch, Event *pEvent);
    void onTouchCancelled(Touch *touch, Event *event);
    
private:
    bool moved_;
};

#endif
//
//  ControlButtonX.cpp
//

#include "ControlButtonX.h"

ControlButtonX::ControlButtonX()
{
}

ControlButton* ControlButtonX::create(Scale9Sprite* sprite)
{
    ControlButtonX *pRet = new ControlButtonX();
    pRet->initWithBackgroundSprite(sprite);
    pRet->autorelease();
    return pRet;
}

bool ControlButtonX::onTouchBegan(Touch *pTouch, Event *pEvent)
{
    moved_=false;
    
    auto parent=getParent();
    if(parent)
    {
        if(auto srollView=dynamic_cast<ScrollView*>(parent->getParent()))
        {
            srollView->onTouchBegan(pTouch,pEvent);
        }
    }

    return ControlButton::onTouchBegan(pTouch,pEvent);
}

void ControlButtonX::onTouchMoved(Touch *pTouch, Event *pEvent)
{
    moved_=true;
    
    ControlButton::onTouchMoved(pTouch,pEvent);
    
    auto parent=getParent();
    if(parent)
    {
        if(auto srollView=dynamic_cast<ScrollView*>(parent->getParent()))
        {
            srollView->onTouchMoved(pTouch,pEvent);
        }
    }
}

void ControlButtonX::onTouchEnded(Touch *pTouch, Event *pEvent)
{
 ScrollView* parentScrollView = nullptr;
 auto parent=getParent();
 if(parent)
 {
 parentScrollView = dynamic_cast<ScrollView*>(parent->getParent());
 }

 if (!parentScrollView)
 {
 ControlButton::onTouchEnded(pTouch, pEvent);
 }
 else
 {
 _isPushed = false;
 setHighlighted(false);

 if(!moved_)
 {
 if (isTouchInside(pTouch))
 {
 sendActionsForControlEvents(Control::EventType::TOUCH_UP_INSIDE);
 }
 else
 {
 sendActionsForControlEvents(Control::EventType::TOUCH_UP_OUTSIDE);
 }
 }
 
 parentScrollView->onTouchEnded(pTouch,pEvent);
 }

 moved_=false;
}

void ControlButtonX::onTouchCancelled(Touch *pTouch, Event *pEvent)
{
    ControlButton::onTouchMoved(pTouch,pEvent);
    
    moved_=false;
}

发表评论