纵向滚动列表无限刷新,横向的稍微修改即可。原理相同。
cc.Class({
extends: cc.Component,
properties: {
itemPref:{
type: cc.Prefab,
default: null,
},
mask:{
type: cc.Node,
default: null,
},
},
// onLoad () {},
//只支持纵向。
//只支持纵向。
//只支持纵向。
start () {
this.itemH = 100; //包括间隙
this.itemTotalNum = 8;
this.visibleSize = this.mask.getContentSize();
this.realItemNum = Math.floor(this.visibleSize.height / this.itemH) + 2;
this.itemArr = [];
//测试数据
this.data = [];
for(var i=0; i<17; i++){
this.data.push("" + i) ;
}
this.initItem();
},
initItem(){
var eventHandler = new cc.Component.EventHandler();
eventHandler.target = this.node;
eventHandler.component = "ScrollHelper";
eventHandler.handler = "onScroll";
this.scroll_com = this.getComponent(cc.ScrollView);
this.scroll_com.scrollEvents.push((eventHandler));
var totalH = this.itemTotalNum*this.itemH;
this.mask.getContentSize()
this.scroll_com.content.setContentSize(this.visibleSize.width, totalH);
this.initObj();
},
initObj(){
for(var i=0; i < this.realItemNum; i++){
var item = cc.instantiate(this.itemPref);
this.scroll_com.content.addChild(item);
item.y = -this.itemH/2 - this.itemH*i;
this.itemArr.push(item);
this.refreshData(i, item)
}
},
onScroll(){
this.refresh();
},
refresh(){
this.currOffset = this.scroll_com.getScrollOffset();
var start_index = Math.floor(this.currOffset.y / this.itemH);
var isOutMax = this.visibleSize.height + this.currOffset.y > (this.itemTotalNum-1)*this.itemH
if (start_index<0 || isOutMax){
return;
}
for(var i=0; i < this.realItemNum; i++){
var item = this.itemArr[i];
var new_y = -this.itemH/2 - this.itemH*(i + start_index);
item.y = new_y;
this.refreshData(i + start_index, item)
}
},
//测试数据
refreshData(dataIndex, item){
var lbl = item.getChildByName("lbl").getComponent(cc.Label);
lbl.string = "aa"+dataIndex;
}
// update (dt) {},
});