import { addBtnClick } from '@scripts/utils/UIHelper'; import { _decorator, Button, Component, EditBox, Label, Node, instantiate } from 'cc'; const { ccclass, property } = _decorator; @ccclass('SelectBox') export class SelectBox extends Component { @property(Label) label: Label; @property(Node) pull_toggle: Node; @property(Node) pull_up: Node; @property(Node) pull_down: Node; @property(Node) item: Node; @property(Node) scroll_view: Node; @property(Node) content: Node; private _current_idx: number = -1; private _data: string[] = []; protected onLoad(): void { addBtnClick(this.pull_toggle, this.onBtnToggleClick, this); } protected onEnable(): void { } protected onDisable(): void { } private init() { this.pull_down.active = true; this.pull_up.active = false; this.content.active = false; this.scroll_view.active = false; this.content.removeAllChildren(); this.label.string = ''; } public initSelectItems(data: string[] = [], params: any = {}) { const selectData = data; this._data = selectData; this.init(); for (let i = 0; i < selectData.length; i++) { const item = instantiate(this.item); item.active = true; item.parent = this.content; item.getChildByName("selected").active = false; item.getChildByName("label").getComponent(Label).string = selectData[i]; addBtnClick(item, () => { this.handleClickItem(i, selectData[i]) }, this); } const { defaultIndex } = params; this.setDefaultIndex(defaultIndex); } public getSelectedStr() { return this.label.string; } private handleClickItem(i: number, data: string) { this.label.string = data; this._current_idx = i; this.onBtnToggleClick(); } private onBtnToggleClick() { this.pull_down.active = !this.pull_down.active; this.pull_up.active = !this.pull_up.active; this.content.active = !this.content.active; this.scroll_view.active = this.content.active; if (this.content.active) { // 标记selected this.content.children.forEach((item, index) => { if (index === this._current_idx) { item.getChildByName("selected").active = true; } else { item.getChildByName("selected").active = false; } }) } } private setDefaultIndex(defaultIndex: number) { if (defaultIndex >= 0) { this._current_idx = defaultIndex; const item = this.content.children[defaultIndex]; item.getChildByName("selected").active = true; this.label.string = this._data[defaultIndex]; } } }