关注微信公众号:每日玩机 获取ios、Android、tv、mac黑科技软件
新建ts文件写入SceneManager工具类,具体如下:
class SceneManager {
private static _manager: SceneManager;
public static get Instance() {
if (SceneManager._manager == null) {
SceneManager._manager = new SceneManager();
}
return SceneManager._manager;
}
public constructor() {
}
public rootLayer: eui.UILayer;//起始场景
private currentScene: Scene;//需要显示的场景
private pop_scene: Scene;//弹出场景层
//切换场景
public changeScene(s: Scene) {
if (this.currentScene) {
this.rootLayer.removeChild(this.currentScene);
this.currentScene = null;
}
this.popScene();
this.rootLayer.addChild(s);
this.currentScene = s;
}
//弹出场景层
public pushScene(s: Scene) {
this.popScene();
if (!this.pop_scene) {
this.rootLayer.addChild(s);
this.pop_scene = s;
}
}
//关闭场景层
public popScene() {
if (this.pop_scene) {
this.rootLayer.removeChild(this.pop_scene);
this.pop_scene = null;
}
}
}
新添加的eui组件得继承Scene
- 新建一个Scene.ts文件
abstract class Scene extends eui.Component{
public constructor() {
super();
// 监听组件创建完毕 也就是场景的外观创建完毕
this.addEventListener(eui.UIEvent.CREATION_COMPLETE,this.onComplete,this);
}
protected abstract onComplete();
}
- 在以后新建的eui组件中ts文件就得继承该Scene,具体改成如下样式,只有是继承Scene的页面才可以使用该工具类进行管理
class page extends Scene {
public constructor() {
super();
}
protected partAdded(partName: string, instance: any): void {
super.partAdded(partName, instance);
}
protected childrenCreated(): void {
super.childrenCreated();
}
protected onComplete(): void {
}
}
具体使用如下
- 第一步也是很重要的一步,初始化第一个场景
调用工具类的rootLayer 设置初始页面
注:
因为我是设置的loading页面为初始页,而loading页时extends的eui.UILayer,所以我在SceneManager 类中设置的rootLayer 也为eui.UILayer,只有这两个类型相同才能初始化成功,具体类型根据自己的需要去设置
SceneManager.Instance.rootLayer = this;
- 切换页面并删除当前页面
var homePage = new home_page();
SceneManager.Instance.changeScene(homePage);
- 弹出页面,不删除当前页面
var homePage = new home_page();
SceneManager.Instance.pushScene(homePage);
- 删除当前页面
SceneManager.Instance.popScene();