本方法只能在CCTableView的扩展类中实现,因为其中的计算方法依赖于CCTableView的protected方法。
具体代码如下:
void scrollToCellIndex(int index) { CCPoint offset = ccpSub(CCPointZero, _offsetFromIndex(index)); float newX, newY; CCPoint maxInset, minInset; maxInset = this->maxContainerOffset(); minInset = this->minContainerOffset(); //check to see if offset lies within the inset bounds newX = MIN(offset.x, maxInset.x); newX = MAX(newX, minInset.x); newY = MIN(offset.y, maxInset.y); newY = MAX(newY, minInset.y); setContentOffset(ccp(newX, newY), true); }
补充:
后来参考其他博文,发现Direction和VerticalFillOrder其实是开放出来的,可以自行计算得到,而不是一定要通过protected function依赖的。
贴上lua方法:
-- 追加滚动到指定位置的方法 -- dataSource需要从外部传入,因为quick-cocos2d-x的CCTableView.toua中没有提供 CCTableViewDataSource* getDataSource() local dataSource = params.dataSource t.scrollToCellIndex = function(self, index) local direction = self:getDirection() local verticalFillOrder = self:getVerticalFillOrder() local offsetX = 0 local offsetY = 0 -- 单元格大小 local cellSize = dataSource:cellSize(self) -- 总数 local itemCounts = dataSource:numberOfCells(self) -- 根据方向计算偏移量 if direction == kCCScrollViewDirectionVertical then if verticalFillOrder == kCCTableViewFillTopDown then offsetY = -cellSize.height * (itemCounts - index - 1) else offsetY = -cellSize.height * index; end else if verticalFillOrder == kCCTableViewFillTopDown then offsetX = -cellSize.width * (itemCounts - index - 1) else offsetX = -cellSize.width * index end end -- 检查偏移量是否越界 local maxInset = self:maxContainerOffset(); local minInset = self:minContainerOffset(); offsetX = math.min(offsetX, maxInset.x); offsetX = math.max(offsetX, minInset.x); offsetY = math.min(offsetY, maxInset.y); offsetY = math.max(offsetY, minInset.y); self:setContentOffset(ccp(offsetX, offsetY), true); end
参考博文:http://blog.csdn.net/wzq9706/article/details/9105915