#pragma once;
#include "cocos2d.h"
#include "cocos-ext.h"
USING_NS_CC;
USING_NS_CC_EXT;
class scrollViewTest:public CCLayer,public CCScrollViewDelegate {
public:
CREATE_FUNC(scrollViewTest);
static cocos2d::CCScene* scene();
virtual bool init();
bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent);
void ccTouchMoved(CCTouch * touch,CCEvent * pEvent);
void ccTouchEnded(CCTouch * touch,CCEvent * pEvent);
void registerWithTouchDispatcher();
CCScrollView* scrollview;
virtual void scrollViewDidScroll (CCScrollView *view);
virtual void scrollViewDidZoom (CCScrollView *view);
};
#include "scrollViewTest.h"
cocos2d::CCScene* scrollViewTest::scene()
{
CCScene * scene=CCScene::create();
scene->addChild(scrollViewTest::create());
return scene;
}
bool scrollViewTest::init()
{
if(!CCLayer::init()){return false;}
CCSize size=CCDirector::sharedDirector()->getWinSize();
CCLayer* layer=CCLayerColor::create(ccc4(255,0,0,255));
for (int i=0;i<5;i++)
{
CCSprite* sprite1=CCSprite::create("HelloWorld.png");
sprite1->setPosition(ccp(size.width*(i+0.5f),size.height/2));
layer->addChild(sprite1,2);
}
//scrollview=CCScrollView::create(size/2,layer); //设置显示的区域
scrollview=CCScrollView::create(size,layer);
scrollview->setDelegate(this);
scrollview->setContentSize(ccp(size.width*5,size.height)); //设置内容的大小
scrollview->setDirection(kCCScrollViewDirectionHorizontal);
scrollview->setContentOffset(CCPoint(0,0));
scrollview->setBounceable(true); //设置有弹性效果
this->addChild(scrollview);
this->setTouchEnabled(true);
return true;
}
void scrollViewTest::registerWithTouchDispatcher()
{
CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this,0,true);}
bool scrollViewTest::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent)
{
return true;
}
void scrollViewTest::ccTouchMoved(CCTouch * touch,CCEvent * pEvent)
{
}
void scrollViewTest::ccTouchEnded(CCTouch * touch,CCEvent * pEvent)
{
CCLOG("ccTouchEnded");
scrollview->unscheduleAllSelectors();
float offsetX=scrollview->getContentOffset().x; //返回的是负数
float winX=CCDirector::sharedDirector()->getWinSize().width;
float div=fabs(offsetX/winX);
int curPage=(int)div;
if(div+0.5>(int)(div+1)){
curPage++;
}
float offx=curPage*(-winX);
CCLOG("%f,%f,%f,%d,%f",offsetX,winX,div,curPage,offx);
scrollview->setContentOffsetInDuration(ccp(offx,0),0.5f);
}
void scrollViewTest::scrollViewDidScroll(CCScrollView *view)
{
//CCLOG("scrollViewDidScroll");
//float offsetX=view->getContentOffset().x; //返回的是负数
//float winX=CCDirector::sharedDirector()->getWinSize().width;
//float div=fabs(offsetX/winX);
//int curPage=(int)div;
//if(div+0.5>(int)(div+1)){
// curPage++;
//}
//*view->setContentOffset(ccp(curPage*(-winX),0)); //会有冲突,不是结束滑动的事件 ,放在父类的touch事件中
//CCLOG("%f,%f,%f,%d",offsetX,winX,div,curPage);
}
void scrollViewTest::scrollViewDidZoom(CCScrollView *view)
{
CCLOG("scrollViewDidZoom");
}