unity程序员转Laya入门(7) 用List制作商店或背包(类似Scroll view)

研究了半天Laya官网的例子,然后各种琢磨,反复试验,最终用下面的方法实现了:

1,制作元素

新建一个场景,类型定义为View.

1.1,制作元素。这里元素用最简单image,和label组成。如图:

1.2,把这个已经组好的元素,变成prefab:具体是选中这个刚生成的Box,然后在属性的右上角,点击【保存预设】

这里我改了一下预设名字,改为Image_item

扫描二维码关注公众号,回复: 14907252 查看本文章

之后会自动在Scene下的prefab文件夹下,生成对应的prefab文件:

预制体已经生成好了,此时在场景内的image_item,可以删除掉了,如下图,场景View下面为空。

2,制作List

2.1 创建UI组件,List。这时候可以调整好List的部分属性,比如位置,大小,等等。

3,写代码

创建脚本文件Test_Laya_List.ts,代码如下:


class Item extends Laya.Box {
    private image_item: Laya.Image;
    // 每次实例化后, List的Box容器下面, 会生成一层itemN(0-N)的次层容器
    constructor(){
        super();
        // 初始化容器大小(容器会自动命名为itemN)
        this.size(470, 118);
        console.log("init item!!------");
    }

    public initImg(item_pref:Laya.Prefab, name_str: string): void {
        // 只有在容器子元素为0, 再动态初始化
        if (this.numChildren ==0){
            this.image_item = Laya.Pool.getItemByCreateFun("image_item", item_pref.create, item_pref); 
            this.addChild(this.image_item);
            // 找到下一层的子控件Label
            let the_bk:Laya.Image = this.getChildByName("image_item") as Laya.Image; 
            let the_label:Laya.Label = the_bk.getChildByName("label_name") as Laya.Label;
            the_label.text = name_str; 
        }
    }
}


export default class Test_Laya_List extends Laya.Script {

    /** @prop {name:item_pref, tips:"元素预制体", type:Prefab}*/
    public item_pref: Laya.Prefab;   // 拖拽进来

    // 示例数据
    private example_data: Array<string> = ["A","B","C","D","E"];
    private laya_list: Laya.List; 
    
    constructor() { super(); }
    
    onEnable(): void {
    }

    onDisable(): void {
    }


    private initList(): void {
        // 由于已经在编辑器里放置好了List, 所以找到即可. (当然也可以像官网示例那样动态生成List)
        this.laya_list = this.owner.getChildByName("list_bag") as Laya.List; 
        this.laya_list.itemRender = Item;
        this.laya_list.repeatX = 1;       // 一行只有1个元素
        // this.laya_list.repeatY = 4;    // 不设置, 默认应该是自动 
        // 使用但隐藏滚动条
        this.laya_list.vScrollBarSkin = "";
        this.laya_list.scrollBar.elasticBackTime = 220;    //设置橡皮筋回弹时间。单位为毫秒。
        this.laya_list.scrollBar.elasticDistance = 150;     //设置橡皮筋极限距离。
        this.laya_list.selectEnable = true;
        this.laya_list.selectHandler = new Laya.Handler(this, this.onSelect);
        this.laya_list.renderHandler = new Laya.Handler(this, this.updateItem);

        // 设置数据
        this.laya_list.array = this.example_data;
    }

    private updateItem(cell: Item, index: number): void {
        // 传入已经做好的UI预制体
        cell.initImg(this.item_pref, this.example_data[index]);
    }
    private onSelect(index: number): void {
        console.log("当前选择的索引:" + index);
    }


    onStart() : void {
        this.initList(); 
    }

}


4,挂载代码并运行

将代码挂载在View上。运行。结果如下:

猜你喜欢

转载自blog.csdn.net/chenggong2dm/article/details/117826669