UIBase.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import { _decorator, Button, Component, Node, PageView } from 'cc';
  2. const { ccclass, property } = _decorator;
  3. export enum UIType{
  4. PAGE,
  5. WIDGET,
  6. POPWIN,
  7. }
  8. @ccclass('UIBase')
  9. export class UIBase extends Component {
  10. protected _nodes: Map<string, Node> = new Map();
  11. protected _uiName: string = "ui";
  12. get UIName(){ return this._uiName;}
  13. set UIName(name: string){this._uiName = name;}
  14. //如果使用ui都要进行相同的初始化
  15. init(){
  16. this._visit(this.node)
  17. //多态
  18. this.onStart();
  19. }
  20. //各个ui都有不同的初始化行为
  21. protected onStart(){
  22. }
  23. private _visit(node: Node){
  24. //如果这个节点的名字是 “ _ ” 开头的 就是需要操作的节点
  25. if(node.name.startsWith("_")){
  26. this._nodes.set(node.name, node);
  27. }
  28. for(const child of node.children){
  29. this._visit(child);
  30. }
  31. }
  32. show(){
  33. this.node.active = true;
  34. this.use();
  35. }
  36. showing(){
  37. return this.node.active;
  38. }
  39. hide(clear: Boolean = true){
  40. this.unUse();
  41. if(clear){
  42. this.node.destroy();
  43. return;
  44. }
  45. this.node.active = false;
  46. }
  47. //多态
  48. //用它的时候
  49. protected use(){
  50. }
  51. //不用它的时候
  52. protected unUse(){
  53. }
  54. //UI 事件
  55. //按钮点击
  56. onBtnClick(name: string, callback: Function, ...arg){
  57. const node = this._nodes.get(name);
  58. if(node){
  59. node.on(Button.EventType.CLICK,()=>{
  60. //apply指定函数的this指向 并且立即执行
  61. //参数1 就是函数执行过程中的this指向
  62. callback.apply(this, [...arg]);
  63. })
  64. }
  65. }
  66. //pageView的事件
  67. onPageView(name: string, type, callback: Function){
  68. this._nodes.get(name).on(type, callback);
  69. }
  70. getPageView(name: string): PageView{
  71. return this._nodes.get(name).getComponent(PageView);
  72. }
  73. getNode(name: string): Node{
  74. return this._nodes.get(name);
  75. }
  76. onMsg(msg: string, callback: Function){
  77. }
  78. }