只要知道了CCTableView的滑动所触发的事件是什么,就好办了。
---------------美丽的分割线-------------------
首先,当我们拖动TableView结束的时候,它有一个自动对齐的函数relocateContainer():
void CCScrollView::relocateContainer(bool animated)
{
CCPoint oldPoint, min, max;
float newX, newY;
min = this->minContainerOffset(); // TableView的显示偏移范围(显示的范围,比如有2个Cell,宽度为40,水平情况下,min为-80,max为0)(下面有图可参考哟)
max = this->maxContainerOffset();
oldPoint = m_pContainer->getPosition(); // 滑动后所处在的偏移位置
newX = oldPoint.x; // 拖动时,TableView偏移的位置
newY = oldPoint.y;
if (m_eDirection == kCCScrollViewDirectionBoth || m_eDirection == kCCScrollViewDirectionHorizontal)
{
newX = MAX(newX, min.x); // 下面解释
newX = MIN(newX, max.x);
}
if (m_eDirection == kCCScrollViewDirectionBoth || m_eDirection == kCCScrollViewDirectionVertical)
{
newY = MIN(newY, max.y);
newY = MAX(newY, min.y);
}
if (newY != oldPoint.y || newX != oldPoint.x)
{
this->setContentOffset(ccp(newX, newY), animated); // 设置目前偏移的位置
}
}
if (m_eDirection == kCCScrollViewDirectionBoth || m_eDirection == kCCScrollViewDirectionHorizontal)
{
newX = MAX(newX, min.x); // 下面解释
newX = MIN(newX, max.x);
}
由于在TableView中的偏移量是用负号增加的,所以MAX(newX,min.x)的作用是让X轴偏移量不超过最大值。
有点绕人,那么我来个示例图吧:
嗯嗯,画的真好看~
这样就可以知道MIN(newX,max.x)的作用是让X轴偏移量不会小于最小值。(按照上面的图的意思就是:不会让cell都移动到右边,而出现空白的地方)
下面一个Y轴的相同道理,就不解释了。
到此,整个对齐的过程就理解了。
---------------美丽的分割线-------------------
我不会告诉你,这里是精华哟:
通常的需求都需要将TableView的滑动按照整个Cell为单位来对齐,超过了一半的Cell宽度,就会自动对齐到下一个Cell。
因此要写一个继承于CCTableVIew的类,就叫做myTableView吧。(貌似这个名字很戳啊0.0)
当然,想直接修改源码也行。
然后重写对齐函数relocateContainer():
void wTableView::relocateContainer(bool animated)
{
CCPoint oldPoint, min, max;
float newX, newY;
min = this->minContainerOffset();
max = this->maxContainerOffset();
oldPoint = m_pContainer->getPosition();
newX = oldPoint.x;
newY = oldPoint.y;
// begen 这里是我们要添加的
if (m_nMoveStepX > 1) {
if (newX < 0)
newX = -int((-newX + m_nMoveStepX / 2) / m_nMoveStepX) * m_nMoveStepX;
else
newX = int((newX + m_nMoveStepX / 2) / m_nMoveStepX) * m_nMoveStepX;
}
if (m_MoveStepY > 1) {
if (newY < 0)
newY = -int((-newY + m_nMoveStepY / 2) / m_nMoveStepY) * m_nMoveStepY;
else
newY = int((newY + m_nMoveStepY / 2) / m_nMoveStepY) * m_nMoveStepY;
}
// end
if (m_eDirection == kCCScrollViewDirectionBoth || m_eDirection == kCCScrollViewDirectionHorizontal)
{
newX = MAX(newX, min.x);
newX = MIN(newX, max.x);
}
if (m_eDirection == kCCScrollViewDirectionBoth || m_eDirection == kCCScrollViewDirectionVertical)
{
newY = MIN(newY, max.y);
newY = MAX(newY, min.y);
}
if (newY != oldPoint.y || newX != oldPoint.x)
{
this->setContentOffset(ccp(newX, newY), animated);
}
}
在这里设置按照多大的偏移量来对齐:
void wTableView::setMoveStepX( int step )
{
m_nMoveStepX = step;
}
void wTableView::setMoveStepY( int step )
{
m_nMoveStepY = step;
}
完。