CCScrollView/CCTableView(CCTableViewDelegate CCTableViewDataSource CCTableView-滑动列表-游戏中大量使用 很重要的一个类)

本文主要是介绍CCScrollView/CCTableView(CCTableViewDelegate CCTableViewDataSource CCTableView-滑动列表-游戏中大量使用 很重要的一个类),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

tableview 

scrollViewDidScroll函数中有一段   ----  即---滑动tableview时触发的函数 : 会将所有显示的cell重新刷新(刷新函数中调用了自定义的tableCellAtIndex

//

    for (unsigned int i=startIdx; i <= endIdx; i++)

    {

        //if ([m_pIndices containsIndex:i])

        if (m_pIndices->find(i) != m_pIndices->end())

        {

            continue;

        }

        this->updateCellAtIndex(i);

    }


updateCellAtIndex(i);中有一段

cell = m_pDataSource->tableCellAtIndex(this, idx);

///

使用例子

class ListViewLayer : 
public cocos2d::CCLayer, 
public cocos2d::extension::CCTableViewDataSource, (关于cell的数据 包括4个虚函数: tableCellSizeForIndex cellSizeForTable tableCellAtIndex numberOfCellsInTableView
public cocos2d::extension::CCTableViewDelegate(继承自CCScrollViewDelegate 又增加了4个触摸回调 包括4个虚函数:tableCellTouchedtableCellHighlighttableCellUnhighlight tableCellWillRecycle)
{
public :
     virtual bool init(); 
///
boolListViewLayer::init()
{
    boolbRet = false;
    do
    {
        CC_BREAK_IF( !CCLayer::init() );
 
        CCTableView* pTableView = CCTableView::create(this, CCSizeMake(960, 640));
        pTableView->setDirection(kCCScrollViewDirectionVertical);
        pTableView->setPosition(CCPointZero);
        pTableView->setDelegate(this);
        pTableView->setVerticalFillOrder(kCCTableViewFillTopDown);
        this->addChild(pTableView);
        pTableView->reloadData();
 
        bRet = true;
    }while(0);
 
    returnbRet;
}
//

     virtual void scrollViewDidScroll(cocos2d::extension::CCScrollView* view);
     virtual void scrollViewDidZoom(cocos2d::extension::CCScrollView* view);
     //处理触摸事件,可以计算点击的是哪一个子项
     virtual void tableCellTouched(cocos2d::extension::CCTableView* table, cocos2d::extension::CCTableViewCell* cell);
// 
voidListViewLayer::tableCellTouched(CCTableView* table, CCTableViewCell* cell)
{
    CCLog("cell touched at index: %i", cell->getIdx());
}
/
//每一项的宽度和高度必须重写的一个虚函数
     virtual cocos2d::CCSize cellSizeForTable(cocos2d::extension::CCTableView *table);
     //生成列表每一项的内容 必须重写的一个虚函数
     virtual cocos2d::extension::CCTableViewCell* tableCellAtIndex(cocos2d::extension::CCTableView *table, unsigned int idx);
CCTableViewCell* ListViewLayer::tableCellAtIndex(CCTableView *table, unsigned intidx)
{
    CCString *pString = CCString::createWithFormat("%d", idx);
     CCTableViewCell *pCell = table->dequeueCell(); //得到一个将要离队(释放)的cell
     if (!pCell) { //如果释放池中没有 就自己创建一个 节约内存
        pCell = newCCTableViewCell();
        pCell->autorelease();
        CCSprite *pSprite = CCSprite::create("listitem.png");
        pSprite->setAnchorPoint(CCPointZero);
        pSprite->setPosition(CCPointZero);
        pCell->addChild(pSprite);
 
        CCLabelTTF *pLabel = CCLabelTTF::create(pString->getCString(), "Arial", 20.0);
        pLabel->setPosition(CCPointZero);
        pLabel->setAnchorPoint(CCPointZero);
        pLabel->setTag(123);
        pCell->addChild(pLabel);
    }
    else
    {
        CCLabelTTF *pLabel = (CCLabelTTF*)pCell->getChildByTag(123);
        pLabel->setString(pString->getCString());
    }
 
    returnpCell;
}
     //一共多少项必须重写的一个虚函数
     virtual unsigned int numberOfCellsInTableView(cocos2d::extension::CCTableView *table);
 /
 
unsignedintListViewLayer::numberOfCellsInTableView(CCTableView *table)
{
    return20;
}
///
     CREATE_FUNC(ListViewLayer);
};

首先需要创建CCTableView,设置它的显示区域和显示方向,这里使用了纵向。设置每个子项的宽度和高度,子项的数量以及每个子项对应的内容。每个子项是一个CCTableViewCell,这里进行了优化,复用了子项对象。
下面是效果图:






#ifndef __CCTABLEVIEW_H__

#define __CCTABLEVIEW_H__


#include "CCScrollView.h"

#include "CCTableViewCell.h"


#include <set>

#include <vector>


NS_CC_EXT_BEGIN


class CCTableView;

class CCArrayForObjectSorting;


typedef enum {

    kCCTableViewFillTopDown,  //靠顶端

    kCCTableViewFillBottomUp

} CCTableViewVerticalFillOrder;  //fill 装满 填充


/**

 * Sole(唯一的) purpose(目的 用途) of this delegate(代表) is to single touch(单点触摸) event in this version.//这个版本仅支持单点触摸

 */

class CCTableViewDelegate : public CCScrollViewDelegate

{

public:

    /**

     * Delegate to respond(做出反应) touch event

     */

    virtual void tableCellTouched(CCTableView* table, CCTableViewCell* cell) = 0;


    /**

     * Delegate to respond a table cell press event.

     */

    virtual void tableCellHighlight(CCTableView* table, CCTableViewCell* cell){};//Highlight 突出 加亮  点击事件


    /**

     * Delegate to respond a table cell release event 

     */

    virtual void tableCellUnhighlight(CCTableView* table, CCTableViewCell* cell){};//松开事件


    /**

     * Delegate called when the cell is about to(即将) be recycled. Immediately

     * after this call the cell will be removed from the scene graph and

     * recycled.

     */

    virtual void tableCellWillRecycle(CCTableView* table, CCTableViewCell* cell){};//cell即将回收事件


};



/**

 * Data source that governs(治理) table backend(后端) data.

 */

class CCTableViewDataSource

{

public:

    virtual ~CCTableViewDataSource() {}


    /**

     * cell size for a given index

     *

     * @param idx the index of a cell to get a size

     * @return size of a cell at given index

     */

    virtual CCSize tableCellSizeForIndex(CCTableView *table, unsigned int idx) {   //得到指定ins的cell的size

        return cellSizeForTable(table);

    };

    /**

     * cell height for a given table.

     */

    virtual CCSize cellSizeForTable(CCTableView *table) {  //cell的size

        return CCSizeZero;

    };

    /**

     * a cell instance at a given index

     *

     * @param idx index to search for a cell

     * @return cell found at idx

     */

    virtual CCTableViewCell* tableCellAtIndex(CCTableView *table, unsigned int idx) = 0;  //得到指定idx的 cell

    /**

     * Returns number of cells in a given table view.

     */

    virtual unsigned int numberOfCellsInTableView(CCTableView *table) = 0;//得到cell数量


};



/**

 * UITableView counterpart(副本) for cocos2d for iphone.

 * this is a very basic, minimal(最低的) implementation(实现) to bring UITableView-like component into(作为组件插入) cocos2d world.

 */

class CCTableView : public CCScrollView, public CCScrollViewDelegate

{

public:

    CCTableView();

    virtual ~CCTableView();


    /**

     * An initialized(初始的) table view object

     */

    static CCTableView* create(CCTableViewDataSource* dataSource, CCSize size); 

    /**

     * An initialized table view object

     */

    static CCTableView*create(CCTableViewDataSource* dataSource, CCSize size, CCNode *container);

//

CCTableView* CCTableView::create(CCTableViewDataSource* dataSource, CCSize size, CCNode *container)

{

    CCTableView *table = new CCTableView();

    table->initWithViewSize(size, container);

    table->autorelease();

    table->setDataSource(dataSource);

    table->_updateCellPositions();

    table->_updateContentSize();

    return table;

}

///


    CCTableViewDataSource* getDataSource() { return m_pDataSource; }

    void setDataSource(CCTableViewDataSource* source) { m_pDataSource = source; }


    CCTableViewDelegate* getDelegate() { return m_pTableViewDelegate; }

    void setDelegate(CCTableViewDelegate* pDelegate) { m_pTableViewDelegate = pDelegate; }


    /**

     * determines how cell is ordered and filled in the view. //确定cell在tableview中如何排列

     */

    void setVerticalFillOrder(CCTableViewVerticalFillOrder order);

    CCTableViewVerticalFillOrder getVerticalFillOrder();



    boolinitWithViewSize(CCSize size, CCNode* container = NULL);

bool CCTableView::initWithViewSize(CCSize size, CCNode* container/* = NULL*/)

{

    if (CCScrollView::initWithViewSize(size,container))

    {

        m_pCellsUsed      = new CCArrayForObjectSorting();

        m_pCellsFreed     = new CCArrayForObjectSorting();

        m_pIndices        = new std::set<unsigned int>();

        m_eVordering      = kCCTableViewFillBottomUp;

        this->setDirection(kCCScrollViewDirectionVertical);

        CCScrollView::setDelegate(this);

        return true;

    }

    return false;

}

    /**

     * Updates the content of the cell at a given index.

     */

    voidupdateCellAtIndex(unsigned int idx);//更新cell

void CCTableView::updateCellAtIndex(unsigned int idx)

{

    if (idx == CC_INVALID_INDEX)

    {

        return;

    }

    unsigned int uCountOfItems = m_pDataSource->numberOfCellsInTableView(this);

    if (0 == uCountOfItems || idx > uCountOfItems-1)

    {

        return;

    }

    CCTableViewCell* cell = this->cellAtIndex(idx);

    if (cell)

    {

        this->_moveCellOutOfSight(cell);

    }

    cell = m_pDataSource->tableCellAtIndex(this, idx);

    this->_setIndexForCell(idx, cell);

    this->_addCellIfNecessary(cell);

}

//


    void insertCellAtIndex(unsigned int idx);//插入新的cell 


    void removeCellAtIndex(unsigned int idx);//移除cell


    void reloadData();//重新下载datasource view 将更新

    /**

     * Dequeues a free cell if available. nil if not.

     */

    CCTableViewCell *dequeueCell();//得到一个将要离队(释放)的cell

///

CCTableViewCell *CCTableView::dequeueCell()

{

    CCTableViewCell *cell;

    if (m_pCellsFreed->count() == 0) {

        cell = NULL;   //如果释放池中没有就返回0

    } else {           //如果释放池中有就返回第一个

        cell = (CCTableViewCell*)m_pCellsFreed->objectAtIndex(0);

        cell->retain();

        m_pCellsFreed->removeObjectAtIndex(0);

        cell->autorelease();

    }

    return cell;

}

//



    /**

     * Returns an existing(目前的) cell at a given index. Returns nil if a cell is nonexistent at the moment of query.

     */

    CCTableViewCell *cellAtIndex(unsigned int idx);//按给定的idx 返回一个cell

CCTableViewCell *CCTableView::cellAtIndex(unsigned int idx)

{

    CCTableViewCell *found = NULL;

    if (m_pIndices->find(idx) != m_pIndices->end())

    {

        found = (CCTableViewCell *)m_pCellsUsed->objectWithObjectID(idx);

    }

    return found;

}

///


    virtual voidscrollViewDidScroll(CCScrollView* view);

//

void CCTableView::scrollViewDidScroll(CCScrollView* view)

{

    unsigned int uCountOfItems = m_pDataSource->numberOfCellsInTableView(this);

    if (0 == uCountOfItems)

    {

        return;

    }

    if(m_pTableViewDelegate != NULL) {

        m_pTableViewDelegate->scrollViewDidScroll(this);

    }

    unsigned int startIdx = 0, endIdx = 0, idx = 0, maxIdx = 0;

    CCPoint offset = ccpMult(this->getContentOffset(), -1);

    maxIdx = MAX(uCountOfItems-1, 0);

    if (m_eVordering == kCCTableViewFillTopDown)

    {

        offset.y = offset.y + m_tViewSize.height/this->getContainer()->getScaleY();

    }

    startIdx = this->_indexFromOffset(offset);

if (startIdx == CC_INVALID_INDEX)

{

startIdx = uCountOfItems - 1;

}

    if (m_eVordering == kCCTableViewFillTopDown)

    {

        offset.y -= m_tViewSize.height/this->getContainer()->getScaleY();

    }

    else

    {

        offset.y += m_tViewSize.height/this->getContainer()->getScaleY();

    }

    offset.x += m_tViewSize.width/this->getContainer()->getScaleX();

    endIdx   = this->_indexFromOffset(offset);

    if (endIdx == CC_INVALID_INDEX)

{

endIdx = uCountOfItems - 1;

}

#if 0 // For Testing.

    CCObject* pObj;

    int i = 0;

    CCARRAY_FOREACH(m_pCellsUsed, pObj)

    {

        CCTableViewCell* pCell = (CCTableViewCell*)pObj;

        CCLog("cells Used index %d, value = %d", i, pCell->getIdx());

        i++;

    }

    CCLog("---------------------------------------");

    i = 0;

    CCARRAY_FOREACH(m_pCellsFreed, pObj)

    {

        CCTableViewCell* pCell = (CCTableViewCell*)pObj;

        CCLog("cells freed index %d, value = %d", i, pCell->getIdx());

        i++;

    }

    CCLog("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");

#endif

    if (m_pCellsUsed->count() > 0)

    {

        CCTableViewCell* cell = (CCTableViewCell*)m_pCellsUsed->objectAtIndex(0);

        idx = cell->getIdx();

        while(idx <startIdx)

        {

            this->_moveCellOutOfSight(cell);

            if (m_pCellsUsed->count() > 0)

            {

                cell = (CCTableViewCell*)m_pCellsUsed->objectAtIndex(0);

                idx = cell->getIdx();

            }

            else

            {

                break;

            }

        }

    }

    if (m_pCellsUsed->count() > 0)

    {

        CCTableViewCell *cell = (CCTableViewCell*)m_pCellsUsed->lastObject();

        idx = cell->getIdx();

        while(idx <= maxIdx && idx > endIdx)

        {

            this->_moveCellOutOfSight(cell);

            if (m_pCellsUsed->count() > 0)

            {

                cell = (CCTableViewCell*)m_pCellsUsed->lastObject();

                idx = cell->getIdx();

            }

            else

            {

                break;

            }

        }

    }

    for (unsigned int i=startIdx; i <= endIdx; i++)

    {

        //if ([m_pIndices containsIndex:i])

        if (m_pIndices->find(i) != m_pIndices->end())

        {

            continue;

        }

        this->updateCellAtIndex(i);

    }

}

//

    virtual void scrollViewDidZoom(CCScrollView* view) {}


    virtual bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent);

    virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent);

    virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent);

    virtual void ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent);


protected:


    CCTableViewCell *m_pTouchedCell;//当前触摸的cell


    CCTableViewVerticalFillOrder m_eVordering;//fill 模式


    /**

     * index set to query the indexes of the cells used.

     */

    std::set<unsigned int>* m_pIndices;//保存cell idx的set


    /**

     * vector with all cell positions

     */

    std::vector<float> m_vCellsPositions;//保存cell position的vector

    //NSMutableIndexSet *indices_;

    /**

     * cells that are currently in the table

     */

    CCArrayForObjectSorting* m_pCellsUsed;// table中当前所有cell

    /**

     * free list of cells

     */

    CCArrayForObjectSorting* m_pCellsFreed;///

    /**

     * weak link to the data source object

     */

    CCTableViewDataSource* m_pDataSource;

    /**

     * weak link to the delegate object

     */

    CCTableViewDelegate* m_pTableViewDelegate;


CCScrollViewDirection m_eOldDirection;


    int __indexFromOffset(CCPoint offset);//根据偏移量得到idx

    unsigned int _indexFromOffset(CCPoint offset);

    CCPoint __offsetFromIndex(unsigned int index);//根据idx得到偏移量

    CCPoint _offsetFromIndex(unsigned int index);


    void _moveCellOutOfSight(CCTableViewCell *cell);

    void _setIndexForCell(unsigned int index, CCTableViewCell *cell);

    void _addCellIfNecessary(CCTableViewCell * cell);///Necessary 必要的


    void_updateCellPositions();//更新cell位置

///

void CCTableView::_updateCellPositions() {

    int cellsCount = m_pDataSource->numberOfCellsInTableView(this);

    m_vCellsPositions.resize(cellsCount + 1, 0.0);

    if (cellsCount > 0)

    {

        float currentPos = 0;

        CCSize cellSize;

        for (int i=0; i < cellsCount; i++)

        {

            m_vCellsPositions[i] = currentPos;

            cellSize = m_pDataSource->tableCellSizeForIndex(this, i);

            switch (this->getDirection())

            {

                case kCCScrollViewDirectionHorizontal:

                    currentPos += cellSize.width;

                    break;

                default:

                    currentPos += cellSize.height;

                    break;

            }

        }

        m_vCellsPositions[cellsCount] = currentPos;//1 extra value allows us to get right/bottom of the last cell

    }

}

public:

    void_updateContentSize();//更新table尺寸

/

void CCTableView::_updateContentSize()

{

    CCSize size = CCSizeZero;

    unsigned int cellsCount = m_pDataSource->numberOfCellsInTableView(this);

    if (cellsCount > 0)

    {

        float maxPosition = m_vCellsPositions[cellsCount];

        switch (this->getDirection())

        {

            case kCCScrollViewDirectionHorizontal:

                size = CCSizeMake(maxPosition, m_tViewSize.height);

                break;

            default:

                size = CCSizeMake(m_tViewSize.width, maxPosition);

                break;

        }

    }

    this->setContentSize(size);

if (m_eOldDirection != m_eDirection)

{

if (m_eDirection == kCCScrollViewDirectionHorizontal)

{

this->setContentOffset(ccp(0,0));

}

else

{

this->setContentOffset(ccp(0,this->minContainerOffset().y));

}

m_eOldDirection = m_eDirection;

}

}

/


};



NS_CC_EXT_END


#endif /* __CCTABLEVIEW_H__ */


这篇关于CCScrollView/CCTableView(CCTableViewDelegate CCTableViewDataSource CCTableView-滑动列表-游戏中大量使用 很重要的一个类)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/661561

相关文章

中文分词jieba库的使用与实景应用(一)

知识星球:https://articles.zsxq.com/id_fxvgc803qmr2.html 目录 一.定义: 精确模式(默认模式): 全模式: 搜索引擎模式: paddle 模式(基于深度学习的分词模式): 二 自定义词典 三.文本解析   调整词出现的频率 四. 关键词提取 A. 基于TF-IDF算法的关键词提取 B. 基于TextRank算法的关键词提取

使用SecondaryNameNode恢复NameNode的数据

1)需求: NameNode进程挂了并且存储的数据也丢失了,如何恢复NameNode 此种方式恢复的数据可能存在小部分数据的丢失。 2)故障模拟 (1)kill -9 NameNode进程 [lytfly@hadoop102 current]$ kill -9 19886 (2)删除NameNode存储的数据(/opt/module/hadoop-3.1.4/data/tmp/dfs/na

Hadoop数据压缩使用介绍

一、压缩原则 (1)运算密集型的Job,少用压缩 (2)IO密集型的Job,多用压缩 二、压缩算法比较 三、压缩位置选择 四、压缩参数配置 1)为了支持多种压缩/解压缩算法,Hadoop引入了编码/解码器 2)要在Hadoop中启用压缩,可以配置如下参数

Makefile简明使用教程

文章目录 规则makefile文件的基本语法:加在命令前的特殊符号:.PHONY伪目标: Makefilev1 直观写法v2 加上中间过程v3 伪目标v4 变量 make 选项-f-n-C Make 是一种流行的构建工具,常用于将源代码转换成可执行文件或者其他形式的输出文件(如库文件、文档等)。Make 可以自动化地执行编译、链接等一系列操作。 规则 makefile文件

使用opencv优化图片(画面变清晰)

文章目录 需求影响照片清晰度的因素 实现降噪测试代码 锐化空间锐化Unsharp Masking频率域锐化对比测试 对比度增强常用算法对比测试 需求 对图像进行优化,使其看起来更清晰,同时保持尺寸不变,通常涉及到图像处理技术如锐化、降噪、对比度增强等 影响照片清晰度的因素 影响照片清晰度的因素有很多,主要可以从以下几个方面来分析 1. 拍摄设备 相机传感器:相机传

pdfmake生成pdf的使用

实际项目中有时会有根据填写的表单数据或者其他格式的数据,将数据自动填充到pdf文件中根据固定模板生成pdf文件的需求 文章目录 利用pdfmake生成pdf文件1.下载安装pdfmake第三方包2.封装生成pdf文件的共用配置3.生成pdf文件的文件模板内容4.调用方法生成pdf 利用pdfmake生成pdf文件 1.下载安装pdfmake第三方包 npm i pdfma

零基础学习Redis(10) -- zset类型命令使用

zset是有序集合,内部除了存储元素外,还会存储一个score,存储在zset中的元素会按照score的大小升序排列,不同元素的score可以重复,score相同的元素会按照元素的字典序排列。 1. zset常用命令 1.1 zadd  zadd key [NX | XX] [GT | LT]   [CH] [INCR] score member [score member ...]

git使用的说明总结

Git使用说明 下载安装(下载地址) macOS: Git - Downloading macOS Windows: Git - Downloading Windows Linux/Unix: Git (git-scm.com) 创建新仓库 本地创建新仓库:创建新文件夹,进入文件夹目录,执行指令 git init ,用以创建新的git 克隆仓库 执行指令用以创建一个本地仓库的

【北交大信息所AI-Max2】使用方法

BJTU信息所集群AI_MAX2使用方法 使用的前提是预约到相应的算力卡,拥有登录权限的账号密码,一般为导师组共用一个。 有浏览器、ssh工具就可以。 1.新建集群Terminal 浏览器登陆10.126.62.75 (如果是1集群把75改成66) 交互式开发 执行器选Terminal 密码随便设一个(需记住) 工作空间:私有数据、全部文件 加速器选GeForce_RTX_2080_Ti

【Linux 从基础到进阶】Ansible自动化运维工具使用

Ansible自动化运维工具使用 Ansible 是一款开源的自动化运维工具,采用无代理架构(agentless),基于 SSH 连接进行管理,具有简单易用、灵活强大、可扩展性高等特点。它广泛用于服务器管理、应用部署、配置管理等任务。本文将介绍 Ansible 的安装、基本使用方法及一些实际运维场景中的应用,旨在帮助运维人员快速上手并熟练运用 Ansible。 1. Ansible的核心概念