最近写CCScrollView遇到很多问题,样式是竖直的类似tableview,在此记录下:
1 CCLayer* layer;
初始化scrollview内容器层
1 layer = CCLayer::create();
设置layer
1 layer->setPosition(ccp(0, -116));
初始化CCScrollView
1 scrollView=CCScrollView::create(CCSizeMake(640, 960-116-160)); 2 scrollView->setPosition(ccp(0,116)); 3 scrollView->setDelegate(this); 4 this->addChild(scrollView); 5 scrollView->setContainer(layer); 6 scrollView->setContentSize(CCSizeMake(640, 960-160)); 7 scrollView->setDirection(kCCScrollViewDirectionVertical); 8 scrollView->setTouchEnabled(false);
校对和调整回滚
1 bool HandbookManager::ccTouchBegan( CCTouch *pTouch, CCEvent *pEvent ) 2 { 3 CCPoint startPos = pTouch->getLocation(); 4 5 return true; 6 } 7 8 void HandbookManager::ccTouchMoved( CCTouch *pTouch, CCEvent *pEvent ) 9 { 10 CCPoint currPos = pTouch->getLocation(); 11 CCPoint prevPos = pTouch->getPreviousLocation(); 12 13 CCLayer * info_listbg = (CCLayer*)scrollView->getContainer(); 14 15 if(scrollView->boundingBox().containsPoint(currPos)) 16 { 17 float y = info_listbg->getPositionY(); 18 info_listbg->setPositionY(y+currPos.y-prevPos.y); 19 } 20 } 21 22 void HandbookManager::ccTouchEnded( CCTouch *pTouch, CCEvent *pEvent ) 23 { 24 CCPoint touchPoint = convertTouchToNodeSpace(pTouch); 25 touchPoint = ccpAdd(this->getPosition(), touchPoint); 26 float dx=fabs(pTouch->getStartLocation().x-pTouch->getLocation().x); 27 float dy=fabs(pTouch->getStartLocation().y-pTouch->getLocation().y); 28 29 if(dx<5 && dy<5){ 30 this->touchPoint(touchPoint); 31 } 32 33 34 CCSprite * s1 = (CCSprite*)layer->getChildByTag(0);//取出层上最上精灵元素 35 CCSprite * s2 = (CCSprite*)layer->getChildByTag(flagTag);//取出层上最下精灵元素元素 36 37 38 p1.y -= 0- layer->getPositionY(); 39 p2.y -= 0- layer->getPositionY()+; 40 41 //firstSpritePosition为层上最上面元素的position 42 //lastSpritePosition 为层上最下面元素的position 43 44 float y1 = firstSpritePosition.y; 45 float y2; 46 if(lastSpritePosition.y>firstSpritePosition.y-scrollView->boundingBox().size.height) 47 y2 = lastSpritePosition.y; 48 else 49 y2 = firstSpritePosition.y-scrollView->boundingBox().size.height; 50 51 if(p1.y <= y1){ 52 CCActionInterval * action = CCMoveBy::create((y1-p1.y)/700,ccp(0,y1-p1.y)); 53 layer->runAction(action); 54 } 55 if(p2.y >= y2){ 56 57 CCActionInterval * action = CCMoveBy::create((p2.y-y2)/700,ccp(0,y2-p2.y)); 58 layer->runAction(action); 59 60 } 61 }
//取得scrollview中点击区域
1 CCRect HandbookManager::getRect(CCNode * pNode) 2 { 3 CCRect rc; 4 rc.origin = pNode->getPosition(); 5 rc.size = pNode->boundingBox().size; 6 rc.origin.x -= rc.size.width*0.5 - layer->getPositionX(); 7 rc.origin.y -= rc.size.height*0.5- layer->getPositionY(); 8 9 rc.origin.x += 0; 10 rc.origin.y += 116; 11 return rc; 12 }