TabSwitching.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. const { ccclass, property } = cc._decorator;
  2. @ccclass
  3. /** 页签切换组件
  4. * - 只对样式进行处理
  5. * - 可注册其他回调,通过'comp-cur-click'事件
  6. * - 可初始化页签,通过'comp-cur-tab'事件
  7. * @author 薛鸿潇
  8. */
  9. export default class TabSwitching extends cc.Component {
  10. /** 页签组 */
  11. @property({ type: cc.Button, displayName: '页签组', tooltip: '按钮target需要有值' })
  12. private arr_btn_tab: cc.Button[] = [];
  13. /** 页签数量 */
  14. private tab_count = 0;
  15. /** 界面点击页签的回调 */
  16. private func = null;
  17. onLoad() {
  18. this.tab_count = this.arr_btn_tab.length;
  19. this.initTabState();
  20. this.initBtnEvent();
  21. /** 页签切换 */
  22. this.node.on('comp-cur-tab', this.curTabType, this);
  23. // 注册界面触摸回调。参数1:函数,参数2:target
  24. this.node.on('comp-cur-click', this.onTabBtnClick, this);
  25. }
  26. start() {
  27. }
  28. /**
  29. * 初始化按钮事件
  30. */
  31. private initBtnEvent() {
  32. for (let i = 0; i < this.tab_count; i++) {
  33. this.arr_btn_tab[i].node.on('click', this.onClockTabCall, this);
  34. }
  35. }
  36. /**
  37. * 页签切换回调
  38. * @param comp_btn 按钮组件
  39. * @param params 参数
  40. */
  41. private onClockTabCall(comp_btn, params?) {
  42. this.initTabState();
  43. let btn_node = comp_btn.node;
  44. let img_style_1 = btn_node.getChildByName('img_style_1');
  45. img_style_1.active = true;
  46. let img_style_2 = btn_node.getChildByName('img_style_2');
  47. img_style_2.active = false;
  48. this.func && this.func(comp_btn, params);
  49. }
  50. /**
  51. * ui界面注册的按钮事件
  52. * @param func 事件
  53. * @param target 目标类
  54. */
  55. private onTabBtnClick(func: Function, target) {
  56. this.func = func.bind(target);
  57. }
  58. /**
  59. * 初始化页签状态
  60. */
  61. private initTabState() {
  62. for (let i = 0; i < this.tab_count; i++) {
  63. let img_style_1 = this.arr_btn_tab[i].node.getChildByName('img_style_1');
  64. img_style_1.active = false;
  65. let img_style_2 = this.arr_btn_tab[i].node.getChildByName('img_style_2');
  66. img_style_2.active = true;
  67. }
  68. }
  69. /**
  70. * 切换到指定页签
  71. * @param tab 页签下标
  72. * @returns
  73. */
  74. private curTabType(tab: number) {
  75. for (let i = 0; i < this.tab_count; i++) {
  76. if (i === tab) {
  77. this.onClockTabCall(this.arr_btn_tab[i], i);
  78. return;
  79. }
  80. }
  81. }
  82. }