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) layout: Node; @property(Node) item: Node; private _current_idx: number = -1; 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.layout.active = false; this.layout.removeAllChildren(); this.label.string = ''; } public initSelectItems(data: string[] = []) { const selectData = data; this.init(); for (let i = 0; i < selectData.length; i++) { const item = instantiate(this.item); item.active = true; item.parent = this.layout; item.getChildByName("selected").active = false; item.getChildByName("label").getComponent(Label).string = selectData[i]; addBtnClick(item, () => { this.handleClickItem(i, selectData[i]) }, this); } } 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.layout.active = !this.layout.active; if (this.layout.active) { // 标记selected this.layout.children.forEach((item, index) => { if (index === this._current_idx) { item.getChildByName("selected").active = true; } else { item.getChildByName("selected").active = false; } }) } } }