LayaBox进阶之UI管理器

自己动手写框架的话,UI管理器是最基础的一部分;

打开界底层是addChild打开的;
 
 
新建一个UIManager
export class UIManager {
    private mainContent: Laya.Sprite;
    private scene: GameScence;
    private uiList:any[];

    constructor() {
        this.mainContent = new Laya.Sprite();

        this.uiList = [];
    }
    }

  mainContent 为默认添加到的层级,

GameScence 为UI管理器默认场景
uiList放所有加载进来的场景
第一步实现 打开界面 openWindow
 
    public openWindow(clazz: any, param?: { data?: any }) {
        let view = new clazz()
        this.setView(clazz, view);
        this.mainContent.addChild(view);
    }

  

  初始化传进来的场景类;
存进字典
添加到显示层
 
下面是缓存的过程 setView
    private setView(clazz: any, view:Laya.Node):void{
        let v: Laya.Node = this.getView(clazz);
        if(!v){
            let uiData = {clazz: clazz, view: view};
            this.uiList.push(uiData);
        }
    }

  首先判断本地缓存有没有,有的话 不处理,没得话,创建,push到数组中

    private getView(clazz: any):Laya.Node{
        for(let i:number =0 ; i<this.uiList.length ; i++){
            let uiData = this.uiList[i];
            if(uiData.clazz == clazz){
                return uiData.view;
            }
        }
    }

  

根据clazz名字获取本地缓存的场景类
 
 
下面是关闭场景,
    public closeWindow(clazz: any): void {
        let v = this.getView(clazz);
        let index: number = this.getViewIndex(clazz);
        if(v){
            v.removeSelf();
            this.uiList.splice(index,1);
        }
    }

  

    private getViewIndex(clazz: any):number{
        for(let i:number =0 ; i<this.uiList.length ; i++){
            let uiData = this.uiList[i];
            if(uiData.clazz == clazz){
                return i;
            }
        }
        return -1;
    }

  

这就是最简单的打开和关闭;
 
还要有一个初始化UIManager的方法, 设置管理器的初始化场景
    public setGameScene(gameScene: GameScence): void {
        this.scene = gameScene;
        if (this.scene) {
            this.scene.parent.addChild(this.mainContent);
        }
    }

  

export let ui: UIManager = new UIManager();
window["ui"] = ui;

  

有时候通过open方法,或者UiManager打开一个场景后,场景里面的元素还不能正常获取;解决办法是
修改Node Sprite的原型, 那么,所有的场景被加载时,都会执行这些方法,
 
import { LogUtil } from "../util/LogUtil";

/**
* 为基类定义若干方法
*/
export class PatchManager{}
(function(){
let _proto:any;

_proto = Laya.Scene.prototype;
_proto.createView = function(view:Object){
if (view && !this._viewCreated) {
this._viewCreated = true;
Laya.SceneUtils.createByData(this, view);
}

this.onInit();
this.onShow();

Laya.timer.frameLoop(1, this, ()=>{
// console.info(this);
this.onUpdate();
});
}

/********************************************************************************
* Node
********************************************************************************/
_proto = Laya.Node.prototype;

_proto.onInit = function(){
}

_proto.onShow = function(){
}

_proto.onUpdate = function(){
}

_proto.onDisable=function(){
this.onHide();
    }

_proto.onHide = function(){
}
})();

  

在场景中 直接写  onShow () {}   界面被加载完成后, 会自动调用这个方法、。
搞定。
原文地址:https://www.cnblogs.com/bobofuns/p/10418143.html