UIBase.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. //true -> 销毁 false -> 不销毁 默认销毁
  40. hide(clear: Boolean = true) {
  41. this.unUse();
  42. if (clear) {
  43. this.node.destroy();
  44. return;
  45. }
  46. this.node.active = false;
  47. }
  48. //多态
  49. //用它的时候
  50. protected use() {
  51. }
  52. //不用它的时候
  53. protected unUse() {
  54. }
  55. //UI 事件
  56. //按钮点击
  57. onBtnClick(name: string, callback: Function, ...arg) {
  58. const node = this._nodes.get(name);
  59. if (node) {
  60. node.on(Button.EventType.CLICK, () => {
  61. //apply指定函数的this指向 并且立即执行
  62. //参数1 就是函数执行过程中的this指向
  63. callback.apply(this, [...arg]);
  64. })
  65. }
  66. }
  67. //pageView的事件
  68. onPageView(name: string, type, callback: Function) {
  69. this._nodes.get(name).on(type, callback);
  70. }
  71. getPageView(name: string): PageView {
  72. return this._nodes.get(name).getComponent(PageView);
  73. }
  74. getNode(name: string): Node {
  75. return this._nodes.get(name);
  76. }
  77. onMsg(msg: string, callback: Function) {
  78. }
  79. }