const { ccclass, property } = cc._decorator; @ccclass /** 页签切换组件 * - 只对样式进行处理 * - 可注册其他回调,通过'comp-cur-click'事件 * - 可初始化页签,通过'comp-cur-tab'事件 * @author 薛鸿潇 */ export default class TabSwitching extends cc.Component { /** 页签组 */ @property({ type: cc.Button, displayName: '页签组', tooltip: '按钮target需要有值' }) private arr_btn_tab: cc.Button[] = []; /** 页签数量 */ private tab_count = 0; /** 界面点击页签的回调 */ private func = null; onLoad() { this.tab_count = this.arr_btn_tab.length; this.initTabState(); this.initBtnEvent(); /** 页签切换 */ this.node.on('comp-cur-tab', this.curTabType, this); // 注册界面触摸回调。参数1:函数,参数2:target this.node.on('comp-cur-click', this.onTabBtnClick, this); } start() { } /** * 初始化按钮事件 */ private initBtnEvent() { for (let i = 0; i < this.tab_count; i++) { this.arr_btn_tab[i].node.on('click', this.onClockTabCall, this); } } /** * 页签切换回调 * @param comp_btn 按钮组件 * @param params 参数 */ private onClockTabCall(comp_btn, params?) { this.initTabState(); let btn_node = comp_btn.node; let img_style_1 = btn_node.getChildByName('img_style_1'); img_style_1.active = true; let img_style_2 = btn_node.getChildByName('img_style_2'); img_style_2.active = false; this.func && this.func(comp_btn, params); } /** * ui界面注册的按钮事件 * @param func 事件 * @param target 目标类 */ private onTabBtnClick(func: Function, target) { this.func = func.bind(target); } /** * 初始化页签状态 */ private initTabState() { for (let i = 0; i < this.tab_count; i++) { let img_style_1 = this.arr_btn_tab[i].node.getChildByName('img_style_1'); img_style_1.active = false; let img_style_2 = this.arr_btn_tab[i].node.getChildByName('img_style_2'); img_style_2.active = true; } } /** * 切换到指定页签 * @param tab 页签下标 * @returns */ private curTabType(tab: number) { for (let i = 0; i < this.tab_count; i++) { if (i === tab) { this.onClockTabCall(this.arr_btn_tab[i], i); return; } } } }