自己嘗試修復
目前只讓insert, update, reload正常使用 (( 限定VERTICAL ))
並且減少從dataResource 呼叫 totalCount t和 cellSize 的次數
CCScrollView.h
新增:
bool _isBouncing;
CCScrollView.cpp
ScrollView::ScrollView()
: _delegate(nullptr)
, _direction(Direction::BOTH)
, _dragging(false)
, _container(nullptr)
, _touchMoved(false)
, _bounceable(false)
, _clippingToBounds(false)
, _touchLength(0.0f)
, _minScale(0.0f)
, _maxScale(0.0f)
, _scissorRestored(false)
, _touchListener(nullptr)
, _isBouncing( false )
{
}
void ScrollView::deaccelerateScrolling(float dt)
{
if (_dragging)
{
this->unschedule(CC_SCHEDULE_SELECTOR(ScrollView::deaccelerateScrolling));
return;
}
float newX, newY;
Vec2 maxInset, minInset;
_container->setPosition(_container->getPosition() + _scrollDistance);
if (_bounceable)
{
maxInset = _maxInset;
minInset = _minInset;
_isBouncing = true;
}
else
{
maxInset = this->maxContainerOffset();
minInset = this->minContainerOffset();
}
newX = _container->getPosition().x;
newY = _container->getPosition().y;
_scrollDistance = _scrollDistance * SCROLL_DEACCEL_RATE;
this->setContentOffset(Vec2(newX,newY));
if ((fabsf(_scrollDistance.x) <= SCROLL_DEACCEL_DIST &&
fabsf(_scrollDistance.y) <= SCROLL_DEACCEL_DIST) ||
newY >= maxInset.y || newY <= minInset.y ||
newX >= maxInset.x || newX <= minInset.x)
{
this->unschedule(CC_SCHEDULE_SELECTOR(ScrollView::deaccelerateScrolling));
this->relocateContainer(true);
}
}
void ScrollView::stoppedAnimatedScroll(Node * node)
{
this->unschedule(CC_SCHEDULE_SELECTOR(ScrollView::performedAnimatedScroll));
_isBouncing = false;
// After the animation stopped, “scrollViewDidScroll” should be invoked, this could fix the bug of lack of tableview cells.
if (_delegate != nullptr)
{
_delegate->scrollViewDidScroll(this);
}
}
CCTableView.h
新增:
protexted:
void _updateCellPosition( size_t index );
void _insertCellPosition( size_t index );
void _removeCellPosition( size_t index );
void _caculateVisibleIdx();
long _cellTotalNum;
int _startIdx;
int _endIdx;
CCTableView.cpp
/****************************************************************************
Copyright © 2012 cocos2d-x.org
Copyright © 2010 Sangwoo Im
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include “CCTableView.h”
#include “CCTableViewCell.h”
NS_CC_EXT_BEGIN
TableView* TableView::create()
{
return TableView::create(nullptr, Size::ZERO);
}
TableView* TableView::create(TableViewDataSource* dataSource, Size size)
{
return TableView::create(dataSource, size, nullptr);
}
TableView* TableView::create(TableViewDataSource* dataSource, Size size, Node *container)
{
TableView *table = new (std::nothrow) TableView();
table->initWithViewSize(size, container);
table->autorelease();
table->setDataSource(dataSource);
table->_updateCellPositions();
table->_updateContentSize();
return table;
}
bool TableView::initWithViewSize(Size size, Node* container/* = nullptr*/)
{
if (ScrollView::initWithViewSize(size,container))
{
CC_SAFE_DELETE(_indices);
_indices = new std::set<ssize_t>();
_vordering = VerticalFillOrder::BOTTOM_UP;
this->setDirection(Direction::VERTICAL);
ScrollView::setDelegate(this);
return true;
}
return false;
}
TableView::TableView()
: _touchedCell(nullptr)
, _indices(nullptr)
, _dataSource(nullptr)
, _tableViewDelegate(nullptr)
, _oldDirection(Direction::NONE)
, _isUsedCellsDirty(false)
, _cellTotalNum(0)
, _startIdx( 0 )
, _endIdx( 0 )
{
}
TableView::~TableView()
{
CC_SAFE_DELETE(_indices);
}
void TableView::setVerticalFillOrder(VerticalFillOrder fillOrder)
{
if (_vordering != fillOrder)
{
_vordering = fillOrder;
if (!_cellsUsed.empty())
{
this->reloadData();
}
}
}
TableView::VerticalFillOrder TableView::getVerticalFillOrder()
{
return _vordering;
}
void TableView::reloadData()
{
_oldDirection = Direction::NONE;
for(const auto &cell : _cellsUsed) {
if(_tableViewDelegate != nullptr) {
_tableViewDelegate->tableCellWillRecycle(this, cell);
}
_cellsFreed.pushBack(cell);
cell->reset();
if (cell->getParent() == this->getContainer())
{
this->getContainer()->removeChild(cell, true);
}
}
_indices->clear();
_cellsUsed.clear();
_cellTotalNum = _dataSource->numberOfCellsInTableView( this );
this->_updateCellPositions();
this->_updateContentSize();
if( _cellTotalNum > 0 )
{
this->scrollViewDidScroll(this);
}
}
TableViewCell *TableView::cellAtIndex(ssize_t idx)
{
if (_indices->find(idx) != _indices->end())
{
for (const auto& cell : _cellsUsed)
{
if (cell->getIdx() == idx)
{
return cell;
}
}
}
return nullptr;
}
void TableView::updateCellAtIndex(ssize_t idx)
{
if (idx == CC_INVALID_INDEX)
{
return;
}
long countOfItems = _cellTotalNum;
if (0 == countOfItems || idx > countOfItems-1)
{
return;
}
TableViewCell* cell = this->cellAtIndex(idx);
if (cell)
{
this->_moveCellOutOfSight(cell);
}
this->_updateCellPosition( idx );
cell = _dataSource->tableCellAtIndex(this, idx);
this->_setIndexForCell(idx, cell);
this->_addCellIfNecessary(cell);
}
void TableView::insertCellAtIndex(ssize_t idx)
{
if (idx == CC_INVALID_INDEX)
{
return;
}
long countOfItems = _cellTotalNum;
if( idx<0 || idx >countOfItems )
{
return;
}
_cellTotalNum++;
for( size_t i = 0; i < _cellsUsed.size(); ++i )
{
TableViewCell* cell = _cellsUsed.at( i );
if( cell->getIdx() >= idx )
{
cell->setIdx( cell->getIdx() + 1 );
}
}
this->_insertCellPosition( idx );
this->_updateContentSize();
_caculateVisibleIdx();
if( idx >= _startIdx && idx <= _endIdx && cellAtIndex( idx ) == NULL )
{
//insert a new cell
TableViewCell* cell = _dataSource->tableCellAtIndex( this, idx );
this->_setIndexForCell( idx, cell );
this->_addCellIfNecessary( cell );
}
Vec2 offset = this->getContentOffset();
if( getDirection() == Direction::HORIZONTAL ? offset.x > 0 : offset.y > 0 )
{
if( !_isBouncing && !_dragging )
setContentOffset( minContainerOffset() );
}
else
{
float cellSize = _vCellsPositions - _vCellsPositions;
switch( this->getDirection() )
{
case Direction::HORIZONTAL:
offset.x -= cellSize;
break;
default:
offset.y -= cellSize;
break;
}
setContentOffset( offset );
}
this->scrollViewDidScroll( this );
}
void TableView::removeCellAtIndex(ssize_t idx)
{
if (idx == CC_INVALID_INDEX)
{
return;
}
long uCountOfItems = _cellTotalNum;
if (0 == uCountOfItems || idx > uCountOfItems-1)
{
return;
}
_cellTotalNum--;
ssize_t newIdx = 0;
TableViewCell* cell = this->cellAtIndex(idx);
if (!cell)
{
return;
}
newIdx = _cellsUsed.getIndex(cell);
//remove first
this->_moveCellOutOfSight(cell);
_indices->erase(idx);
this->_removeCellPosition( idx );
for (ssize_t i = _cellsUsed.size()-1; i > newIdx; i--)
{
cell = _cellsUsed.at(i);
this->_setIndexForCell(cell->getIdx()-1, cell);
}
this->scrollViewDidScroll( this );
}
TableViewCell *TableView::dequeueCell()
{
TableViewCell *cell;
if (_cellsFreed.empty()) {
cell = nullptr;
} else {
cell = _cellsFreed.at(0);
cell->retain();
_cellsFreed.erase(0);
cell->autorelease();
}
return cell;
}
void TableView::_addCellIfNecessary(TableViewCell * cell)
{
if (cell->getParent() != this->getContainer())
{
this->getContainer()->addChild(cell);
}
_cellsUsed.pushBack(cell);
_indices->insert(cell->getIdx());
_isUsedCellsDirty = true;
}
void TableView::_updateContentSize()
{
Size size = Size::ZERO;
ssize_t cellsCount = _cellTotalNum;
if (cellsCount > 0)
{
float maxPosition = _vCellsPositions;
switch (this->getDirection())
{
case Direction::HORIZONTAL:
size = Size(maxPosition, _viewSize.height);
break;
default:
size = Size(_viewSize.width, maxPosition);
break;
}
}
this->setContentSize(size);
if (_oldDirection != _direction)
{
if (_direction == Direction::HORIZONTAL)
{
this->setContentOffset(Vec2(0,0));
}
else
{
this->setContentOffset(Vec2(0,this->minContainerOffset().y));
}
_oldDirection = _direction;
}
}
Vec2 TableView::_offsetFromIndex(ssize_t index)
{
Vec2 offset = this->__offsetFromIndex(index);
const Size cellSize = _dataSource->tableCellSizeForIndex(this, index);
if (_vordering == VerticalFillOrder::TOP_DOWN)
{
offset.y = this->getContainer()->getContentSize().height -offset.y - cellSize.height;
}
return offset;
}
Vec2 TableView::__offsetFromIndex(ssize_t index)
{
Vec2 offset;
Size cellSize;
switch (this->getDirection())
{
case Direction::HORIZONTAL:
offset = Vec2( _vCellsPositions, 0.0f );
break;
default:
offset = Vec2( 0.0f, _vCellsPositions );
break;
}
return offset;
}
long TableView::_indexFromOffset(Vec2 offset)
{
long index = 0;
const long maxIdx = _cellTotalNum - 1;
if (_vordering == VerticalFillOrder::TOP_DOWN)
{
offset.y = this->getContainer()->getContentSize().height - offset.y;
}
index = this->__indexFromOffset(offset);
if (index != -1)
{
index = MAX(0, index);
if (index > maxIdx)
{
index = CC_INVALID_INDEX;
}
}
return index;
}
long TableView::__indexFromOffset(Vec2 offset)
{
long low = 0;
long high = _cellTotalNum - 1;
float search;
switch (this->getDirection())
{
case Direction::HORIZONTAL:
search = offset.x;
break;
default:
search = offset.y;
break;
}
while (high >= low)
{
long index = low + (high - low) / 2;
if( index + 1 >= _vCellsPositions.size() )
return index;
float cellStart = _vCellsPositions;
float cellEnd = _vCellsPositions;
if (search >= cellStart && search <= cellEnd)
{
return index;
}
else if (search < cellStart)
{
high = index - 1;
}
else
{
low = index + 1;
}
}
if (low <= 0) {
return 0;
}
return -1;
}
void TableView::_moveCellOutOfSight(TableViewCell *cell)
{
if(_tableViewDelegate != nullptr) {
_tableViewDelegate->tableCellWillRecycle(this, cell);
}
_cellsFreed.pushBack(cell);
_cellsUsed.eraseObject(cell);
_isUsedCellsDirty = true;
_indices->erase(cell->getIdx());
cell->reset();
if (cell->getParent() == this->getContainer())
{
this->getContainer()->removeChild(cell, true);;
}
}
void TableView::_setIndexForCell(ssize_t index, TableViewCell *cell)
{
cell->setAnchorPoint(Vec2(0.0f, 0.0f));
cell->setPosition(this->_offsetFromIndex(index));
cell->setIdx(index);
}
void TableView::_updateCellPositions()
{
long cellsCount = _cellTotalNum;
_vCellsPositions.resize(cellsCount + 1, 0.0);
if (cellsCount > 0)
{
float currentPos = 0;
Size cellSize;
for (int i=0; i < cellsCount; i++)
{
_vCellsPositions* = currentPos;
cellSize = _dataSource->tableCellSizeForIndex(this, i);
switch (this->getDirection())
{
case Direction::HORIZONTAL:
currentPos += cellSize.width;
break;
default:
currentPos += cellSize.height;
break;
}
}
_vCellsPositions = currentPos;//1 extra value allows us to get right/bottom of the last cell
}
}
void TableView::_updateCellPosition( size_t index )
{
float oldPos = _vCellsPositions;
float oldOffset = _vCellsPositions - oldPos;
Size cellSize = _dataSource->tableCellSizeForIndex( this, index );
float dOffSet = 0.0f;
switch( this->getDirection() )
{
case Direction::HORIZONTAL:
dOffSet = cellSize.width - oldOffset;
break;
default:
dOffSet = cellSize.height - oldOffset;
break;
}
for( size_t i = index +1; i < _vCellsPositions.size(); i++ )
{
_vCellsPositions* += dOffSet;
}
}
void TableView::_insertCellPosition( size_t index )
{
long cellsCount = _cellTotalNum;
_vCellsPositions.resize( cellsCount + 1, 0.0 );
Size cellSize = _dataSource->tableCellSizeForIndex( this, index );
for( size_t i = _vCellsPositions.size() - 1; i > index; --i )
{
switch( this->getDirection() )
{
case Direction::HORIZONTAL:
_vCellsPositions* = _vCellsPositions* + cellSize.width;
break;
default:
_vCellsPositions* = _vCellsPositions* + cellSize.height;
break;
}
}
}
void TableView::_removeCellPosition( size_t index )
{
for( size_t i = index; i < _vCellsPositions.size() -1; ++i )
{
_vCellsPositions* = _vCellsPositions*;
}
_vCellsPositions.resize( _vCellsPositions.size() - 1, 0.0 );
}
void TableView::scrollViewDidScroll(ScrollView* view)
{
long countOfItems = _cellTotalNum;
if (0 == countOfItems)
{
return;
}
if (_isUsedCellsDirty)
{
_isUsedCellsDirty = false;
std::sort(_cellsUsed.begin(), _cellsUsed.end(), ](TableViewCell *a, TableViewCell *b) -> bool{
return a->getIdx() < b->getIdx();
});
}
if(_tableViewDelegate != nullptr) {
_tableViewDelegate->scrollViewDidScroll(this);
}
ssize_t /*startIdx = 0, endIdx = 0, */idx = 0, maxIdx = 0;
Vec2 offset = this->getContentOffset() * -1;
maxIdx = MAX(countOfItems-1, 0);
_caculateVisibleIdx();
#if 0 // For Testing.
Ref* pObj;
int i = 0;
CCARRAY_FOREACH(_cellsUsed, pObj)
{
TableViewCell* pCell = static_cast<TableViewCell*>(pObj);
log(“cells Used index %d, value = %d”, i, pCell->getIdx());
i++;
}
log("---------------------------------------");
i = 0;
CCARRAY_FOREACH(_cellsFreed, pObj)
{
TableViewCell* pCell = static_cast<TableViewCell*>(pObj);
log(“cells freed index %d, value = %d”, i, pCell->getIdx());
i++;
}
log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
#endif
if (!_cellsUsed.empty())
{
auto cell = _cellsUsed.at(0);
idx = cell->getIdx();
while( idx < _startIdx )
{
this->_moveCellOutOfSight(cell);
if (!_cellsUsed.empty())
{
cell = _cellsUsed.at(0);
idx = cell->getIdx();
}
else
{
break;
}
}
}
if (!_cellsUsed.empty())
{
auto cell = _cellsUsed.back();
idx = cell->getIdx();
while( idx <= maxIdx && idx > _endIdx )
{
this->_moveCellOutOfSight(cell);
if (!_cellsUsed.empty())
{
cell = _cellsUsed.back();
idx = cell->getIdx();
}
else
{
break;
}
}
}
for( long i = _startIdx; i <= _endIdx; i++ )
{
TableViewCell* cell = cellAtIndex( i );
if( !cell )
{
cell = _dataSource->tableCellAtIndex( this, i );
cell->setIdx( i );
cell->setAnchorPoint( Vec2( 0.0f, 0.0f ) );
this->_addCellIfNecessary( cell );
}
Size cSize = this->getContainer()->getContentSize();
Vec2 pos;
switch( this->getDirection() )
{
case Direction::HORIZONTAL:
pos.x = cSize.width - _vCellsPositions*;
break;
default:
pos.y = cSize.height - _vCellsPositions*;
break;
}
cell->setPosition( pos );
}
}
void TableView::onTouchEnded(Touch *pTouch, Event *pEvent)
{
if (!this->isVisible()) {
return;
}
if (_touchedCell){
Rect bb = this->getBoundingBox();
bb.origin = _parent->convertToWorldSpace(bb.origin);
if (bb.containsPoint(pTouch->getLocation()) && _tableViewDelegate != nullptr)
{
_tableViewDelegate->tableCellUnhighlight(this, _touchedCell);
_tableViewDelegate->tableCellTouched(this, _touchedCell);
}
_touchedCell = nullptr;
}
ScrollView::onTouchEnded(pTouch, pEvent);
}
bool TableView::onTouchBegan(Touch *pTouch, Event *pEvent)
{
for (Node *c = this; c != nullptr; c = c->getParent())
{
if (!c->isVisible())
{
return false;
}
}
bool touchResult = ScrollView::onTouchBegan(pTouch, pEvent);
if(_touches.size() == 1)
{
long index;
Vec2 point;
point = this->getContainer()->convertTouchToNodeSpace(pTouch);
index = this->_indexFromOffset(point);
if (index == CC_INVALID_INDEX)
{
_touchedCell = nullptr;
}
else
{
_touchedCell = this->cellAtIndex(index);
}
if (_touchedCell && _tableViewDelegate != nullptr)
{
_tableViewDelegate->tableCellHighlight(this, _touchedCell);
}
}
else if (_touchedCell)
{
if(_tableViewDelegate != nullptr)
{
_tableViewDelegate->tableCellUnhighlight(this, _touchedCell);
}
_touchedCell = nullptr;
}
return touchResult;
}
void TableView::onTouchMoved(Touch *pTouch, Event *pEvent)
{
ScrollView::onTouchMoved(pTouch, pEvent);
if (_touchedCell && isTouchMoved())
{
if(_tableViewDelegate != nullptr)
{
_tableViewDelegate->tableCellUnhighlight(this, _touchedCell);
}
_touchedCell = nullptr;
}
}
void TableView::onTouchCancelled(Touch *pTouch, Event *pEvent)
{
ScrollView::onTouchCancelled(pTouch, pEvent);
if (_touchedCell)
{
if(_tableViewDelegate != nullptr)
{
_tableViewDelegate->tableCellUnhighlight(this, _touchedCell);
}
_touchedCell = nullptr;
}
}
void TableView::_caculateVisibleIdx()
{
Vec2 offset = this->getContentOffset() * -1;
if( _vordering == VerticalFillOrder::TOP_DOWN )
{
offset.y = offset.y + _viewSize.height / this->getContainer()->getScaleY();
}
_startIdx = this->_indexFromOffset( offset );
if( _startIdx == CC_INVALID_INDEX )
{
_startIdx = _cellTotalNum - 1;
}
if( _vordering == VerticalFillOrder::TOP_DOWN )
{
offset.y -= _viewSize.height / this->getContainer()->getScaleY();
}
else
{
offset.y += _viewSize.height / this->getContainer()->getScaleY();
}
offset.x += _viewSize.width / this->getContainer()->getScaleX();
_endIdx = this->_indexFromOffset( offset );
if( _endIdx == CC_INVALID_INDEX )
{
_endIdx = _cellTotalNum - 1;
}
}
NS_CC_EXT_END