您的位置:首页 > 移动开发 > Cocos引擎

cocos2dx 3.x TableView多行多列的使用

2017-08-18 18:36 639 查看
前言:当学会使用之后,你会爱上这个控件,无法自拔!

一直使用cc.ScrollView会遇到一个瓶颈,就是数量过多时,滑动肯定会卡。因为它是一开始就创建了所有需要滑动的节点。

而cc.TableView则不一样,它仿造了IOS的UITableView的方式,只创建界面上所看到的TableViewCell,滑动的时候,消失的Cell放入空闲数组,需要显示的Cell就从空闲数组取,直到空闲数组为空才会去创建。

这样极大的节省了内存,但是通过实践才知道,当需要用一个可滑动的多行多列的cc.TableView时,需要做的逻辑是比cc.ScrollView繁琐的,而且你如果没用过的话,就会一连串的掉到坑里面去。

单行单列还不会的同学,可以看一下官方例子,例子路径在引擎下tests\cpp-tests\Classes\ExtensionsTest\TableViewTest,里面有基本的用法。

这里简要介绍一下多行多列的做法,我们先看个图:



由图可知,这里是把一行当做一个TableViewCell,然后用这个TableViewCell去添加四个节点(如果是四列),分别添加到对应的位置。原理很简单,但需要注意的是每个TableViewCell必须有四个节点,如果你的总数不是4的倍数,也就是最后一行需要显示的不是四个,在初始化的时候也需要添加四个节点,因为一旦只添加三个,那么在滑动复用的时候,如果去更新节点数据的话,就会有节点缺失的错误。至于最后一列如果不是四个,那么根据Table的idx对应的只显示总数/4的余数的节点就OK了。

上代码吧:

(我用的是js,引擎是3.11.1版本的)

var TableViewLayer = cc.Layer.extend({
_tableView:null,
ctor: function(){
this._super();
this._init();
},
_init: function(){
this._tableView = new cc.TableView(this,cc.size(960,370));
this._tableView.setDirection(cc.SCROLLVIEW_DIRECTION_VERTICAL);
this._tableView.setDelegate(this);
this._tableView.setVerticalFillOrder(cc.TABLEVIEW_FILL_TOPDOWN);
this._tableView.setPosition(0,0);
this.addChild(this._tableView);
},
//cell的touch事件
tableCellTouched:function (table, cell) {
cc.log("cell touched at index: " + cell.getIdx());
},
//指定每一个Cell的大小,一般来说是统一的
tableCellSizeForIndex:function (table, idx) {
return cc.size(960+5, 153+5);
},

//核心函数,Table滚动的回调
tableCellAtIndex:function (table, idx) {
var strValue = idx.toFixed(0);
var cell = table.dequeueCell();    //从空闲数组中取cell
var label;
if (!cell) {                       //取不到则创建
cell = new CustomTableViewCell(idx);
} else {                           //取到则复用,更新自己所需要更新的UI或数据
label = cell.getChildByTag(123);
label.setString(strValue);
cell.updateData(idx);          //必要:滑动时用来 更新UI显示或是数据
}
return cell;
},

numberOfCellsInTableView:function (table) {
return 10;                        //这里确定TableViewCell的数量
}
})


上述代码功能和单行单列的大致一样,重点区别是TableViewCell,其中Pic是自定义类,可以传入相关参数或数据以便于初始化。

var CustomTableViewCell = cc.TableViewCell.extend({
_xGap:12,
_sprList:null,
ctor: function(idx){
this._super();
this._sprList = [];
this._init(idx);
},
draw:function (ctx) {
this._super(ctx);
},
_init: function(idx){
var strValue = idx.toFixed(0);
for(var i = 0; i < 4; i++){
//var sprite = new cc.Sprite(res.NT01_png);

var sprite = new Pic(parseInt(idx * 4) + parseInt(i));
sprite.anchorX = 0;
sprite.anchorY = 0;
sprite.x = sprite.getContentSize().width * i + this._xGap*i;
sprite.y = 0;
this.addChild(sprite);
this._sprList.push(sprite);

}
var label = new cc.LabelTTF(strValue, "Helvetica", 20.0);
label.x = 0;
label.y = 0;
label.anchorX = 0;
label.anchorY = 0;
label.tag = 123;
this.addChild(label);
},
updateData: function(idx){
for(var i in this._sprList){
var spr = this._sprList[i];
var lab = spr.getChildByTag(123);
lab.setString(idx * 4 + parseInt(i));
}
}
});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: