UIBase.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. import { _decorator, Button, Component, Label, Node, PageView, Sprite } 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. getSprite(name: string): Sprite{
  78. return this.getNode(name).getComponent(Sprite);
  79. }
  80. getLabel(name: string): Label{
  81. return this.getNode(name).getComponent(Label);
  82. }
  83. onMsg(msg: string, callback: Function) {
  84. }
  85. }