CCScene* T25ScrollView::scene()
{
CCScene *scene=CCScene::create();
T25ScrollView* layer=T25ScrollView::create();
scene->addChild(layer);
return scene;
}
bool T25ScrollView::init()
{
CCLayer::init();
CCNode *node=CCNode::create();
_node=node;
char buf[]="a";
for (int i=0;i<5;i++)
{
CCSprite *s=CCSprite::create("HelloWorld.png");
node->addChild(s);
s->setPosition(ccp(i*winSize.width,0));
s->setAnchorPoint(ccp(0,0));
CCLabelTTF *label=CCLabelTTF::create(buf,"Arial",24);
buf[0]++;
s->addChild(label);
label->setPosition(ccp(winSize.width/2,winSize.height/2));
}
CCScrollView *view=CCScrollView::create(winSize,node);
addChild(view);
view->setDirection(kCCScrollViewDirectionHorizontal);
view->setContentSize(CCSizeMake(winSize.width*5,winSize.height));
view->setBounceable(false); //get rid of elastic
setTouchEnabled(true);
setTouchMode(kCCTouchesOneByOne);
return true;
}
bool T25ScrollView::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent)
{
return true;
}
void T25ScrollView::adjustViewPosition(float dt)
{
//calculate
int fitPos[]={0,-winSize.width,-winSize.width*2,-winSize.width*3,-winSize.width*4};
int x=_node->getPositionX();
int i;
for(i=0;i<5;i++)
{
int dist=abs(fitPos[i]-x);
if (dist<winSize.width/2)
{
break;
}
}
CCPoint ptDest=ccp(fitPos[i],0);
_node->runAction(CCMoveTo::create(0.2f,ptDest));
}
void T25ScrollView::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent)
{
//judge if is slider
if (isSlider(pTouch))
{
//adjust position
scheduleOnce(schedule_selector(T25ScrollView::adjustViewPosition),0.05f);
return;
}
//judge which position is clicked
CCPoint ptWorld=pTouch->getLocation();
CCPoint ptNode=_node->convertToNodeSpace(ptWorld);
int index=ptNode.x/winSize.width;
CCLog("click index =%d",index);
}
bool T25ScrollView::isSlider(CCTouch *PTouch)
{
CCPoint ptCur=PTouch->getLocation();
CCPoint ptStart=PTouch->getStartLocation();
if (ptCur.getDistanceSq(ptStart)>25)
{
return true;
}
return false;
}
TableView实现
#include "T26TableView.h"
#include "AppMacros.h"
CCScene* T26TableView::scene()
{
CCScene *scene=CCScene::create();
T26TableView* layer=T26TableView::create();
scene->addChild(layer);
return scene;
}
bool T26TableView::init()
{
CCLayer::init();
CCSize cellSize=CCSize(80,80);
_cells=CCArray::create();
_cells->retain();
for(int i=0;i<5;i++)
{
CCTableViewCell *cell=new CCTableViewCell;
_cells->addObject(cell);
cell->autorelease();
CCSprite *sprite=CCSprite::create("p_2_01.png");
cell->addChild(sprite);
sprite->setPosition(ccp(cellSize.width/2,cellSize.height/2));
}
CCTableView *view=CCTableView::create(this,CCSize(cellSize.width*3,cellSize.height));
addChild(view);
view->setDirection(kCCScrollViewDirectionHorizontal);
view->reloadData();
view->setPosition(ccp(200,200));
view->setDelegate(this);
return true;
}
其中在TableView中使用了代理的设计模式,类要继承public CCTableViewDataSource,public CCTableViewDelegate,并且实现他们的纯虚函数,从而达到代理的效果
运行效果
![结果](https://img-blog.csdn.net/20160308131030255)