Tabbar.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { Component, EventHandler, Node, SystemEventType, _decorator } from "cc";
  2. const { ccclass, property } = _decorator;
  3. /**
  4. * 选项卡组件
  5. * @author 袁浩
  6. */
  7. @ccclass("Tabbar")
  8. export class Tabbar extends Component {
  9. @property({ tooltip: "选中后显示的节点", type: Node })
  10. public checkedNode: Node;
  11. @property({ tooltip: "未选中显示的节点", type: Node })
  12. public uncheckedNode: Node;
  13. @property({ tooltip: "分组" })
  14. public group: string = 'tabbar';
  15. @property({ visible: false })
  16. private _isChecked = false;
  17. @property({ tooltip: "是否选中" })
  18. public get isChecked(): boolean {
  19. return this._isChecked;
  20. }
  21. public set isChecked(value: boolean) {
  22. this._isChecked = value;
  23. this.checkedNode && (this.checkedNode.active = true);
  24. this.uncheckedNode && (this.uncheckedNode.active = false);
  25. }
  26. @property({ tooltip: "选中回调", type: EventHandler })
  27. public checkEvents: EventHandler[] = [];
  28. private static groupData: Map<string, Map<Tabbar, boolean>> = new Map<string, Map<Tabbar, boolean>>();
  29. start() {
  30. this.checkData.set(this, this.isChecked);
  31. this.uncheckedNode.on(SystemEventType.TOUCH_END, this.onUnChecked, this);
  32. }
  33. onDestroy() {
  34. this.checkData.delete(this);
  35. }
  36. get checkData() {
  37. let checkData = Tabbar.groupData.get(this.group);
  38. checkData = checkData || new Map<Tabbar, boolean>();
  39. Tabbar.groupData.set(this.group, checkData);
  40. return checkData;
  41. }
  42. private onUnChecked() {
  43. this.checkData.forEach((isChecked: boolean, tabbar: Tabbar) => {
  44. if (tabbar == this) {
  45. if (!this._isChecked && this.checkEvents) {
  46. for (let i = 0; i < this.checkEvents.length; i++) {
  47. this.checkEvents[i].emit([this]);
  48. }
  49. }
  50. this._isChecked = true;
  51. this.checkedNode.active = true;
  52. this.uncheckedNode.active = false;
  53. }
  54. else {
  55. tabbar.checkedNode.active = false;
  56. tabbar.uncheckedNode.active = true;
  57. tabbar._isChecked = false;
  58. }
  59. });
  60. }
  61. }