cocos creator學習16——滾動列表資料的動態載入
阿新 • • 發佈:2021-01-12
製作預製體
為content新增layout元件
為scrollview中的content節點新增Layout元件,type屬性設定為垂直(VERTICAL
)佈局,Resize Mode屬性設定為CONTAINER
屬性準備
properties: {
HIGH:80, //每一項的高度
PAGE_NUM:8, //每一頁8個項
item_prefab:{ //項的資源預製體
type:cc.Prefab,
default:null,
},
scroll_view:{ //獲取scrollview元件
type:cc.ScrollView,
default:null,
},
程式碼實現
onLoad初始化載入項
onLoad () {
this.value_set=[];
for(var i=1;i<=100;i++)
{
this.value_set.push(i);
}
this.content = this.scroll_view.content;
this.opt_item_set = [];
//每次載入3頁
for(var i=0;i<this.PAGE_NUM*3;i++)
{
var item = cc.instantiate(this.item_prefab);
this.content.addChild(item);
this.opt_item_set.push(item);
}
this.scroll_view.node.on("scroll-ended",this.on_scroll_ended.bind(this),this);//監聽scrollview事件
},
實現顯示記錄
load_recode:function(start_index){
this.start_index=start_index;
for(var i = 0;i<this.PAGE_NUM*3;i++){
var label = this.opt_item_set[i].getChildByName("Label").getComponent(cc.Label);
//顯示記錄
label.string = this.value_set[this.start_index+i];
}
},
在start中編寫索引
start () {
this.start_y = this.content.y;//初始化起始y座標
this.start_index = 0; //100項資料裡面的起始資料記錄索引
this.load_recode(this.start_index);
},
動態載入核心程式碼
於update(dt)
中持續呼叫
load_scroll_recode:function(){
//向下載入資料
//當開始位置比value_set的長度小則代表沒載入完
if(this.start_index + this.PAGE_NUM * 3 < this.value_set.length &&
this.content.y >= this.start_y + this.PAGE_NUM * 2 * this.HIGH)//content超過2個PAGE的高度
{
//_autoScrolling在引擎原始碼中負責處理scrollview的滾動動作
if(this.scroll_view._autoScrolling){ //等自動滾動結束後再載入防止滾動過快,直接跳到非常後的位置
this.scroll_view.elastic = false; //關閉回彈效果 美觀
return;
}
var down_loaded = this.PAGE_NUM;
this.start_index += down_loaded;
if(this.start_index + this.PAGE_NUM * 3>this.value_set.length)
{
//超過資料範圍的長度
var out_len = this.start_index + this.PAGE_NUM * 3 - this.value_set.length;
down_loaded -= out_len;
this.start_index -= out_len;
}
this.load_recode(this.start_index);
this.content.y -= down_loaded * this.HIGH;
return;
}
//向上載入
if(this.start_index>0 && this.content.y<=this.start_y)
{
if(this.scroll_view._autoScrolling){
this.scroll_view.elastic = false;
return;
}
var up_loaded = this.PAGE_NUM;
this.start_index -= up_loaded;
if(this.start_index<0){
up_loaded +=this.start_index;
this.start_index=0;
}
this.load_recode(this.start_index);
this.content.y += up_loaded * this.HIGH;
}
},
on_scroll_ended:function(){
this.load_scroll_recode();
this.scroll_view.elastic = true; //載入結束後自動滾動回彈開啟
},
update (dt) {
this.load_scroll_recode();
},
效果:
自動載入100項資料就完成啦
不錯可以借鑑
https://blog.csdn.net/agsgh/article/details/80140634