SelectBox.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import { addBtnClick } from '@scripts/utils/UIHelper';
  2. import { _decorator, Button, Component, EditBox, Label, Node, instantiate } from 'cc';
  3. const { ccclass, property } = _decorator;
  4. @ccclass('SelectBox')
  5. export class SelectBox extends Component {
  6. @property(Label)
  7. label: Label;
  8. @property(Node)
  9. pull_toggle: Node;
  10. @property(Node)
  11. pull_up: Node;
  12. @property(Node)
  13. pull_down: Node;
  14. @property(Node)
  15. layout: Node;
  16. @property(Node)
  17. item: Node;
  18. private _current_idx: number = -1;
  19. protected onLoad(): void {
  20. addBtnClick(this.pull_toggle, this.onBtnToggleClick, this);
  21. }
  22. protected onEnable(): void {
  23. }
  24. protected onDisable(): void {
  25. }
  26. private init() {
  27. this.pull_down.active = true;
  28. this.pull_up.active = false;
  29. this.layout.active = false;
  30. this.layout.removeAllChildren();
  31. this.label.string = '';
  32. }
  33. public initSelectItems(data: string[] = []) {
  34. const selectData = data;
  35. this.init();
  36. for (let i = 0; i < selectData.length; i++) {
  37. const item = instantiate(this.item);
  38. item.active = true;
  39. item.parent = this.layout;
  40. item.getChildByName("selected").active = false;
  41. item.getChildByName("label").getComponent(Label).string = selectData[i];
  42. addBtnClick(item, () => { this.handleClickItem(i, selectData[i]) }, this);
  43. }
  44. }
  45. public getSelectedStr() {
  46. return this.label.string;
  47. }
  48. private handleClickItem(i: number, data: string) {
  49. this.label.string = data;
  50. this._current_idx = i;
  51. this.onBtnToggleClick();
  52. }
  53. private onBtnToggleClick() {
  54. this.pull_down.active = !this.pull_down.active;
  55. this.pull_up.active = !this.pull_up.active;
  56. this.layout.active = !this.layout.active;
  57. if (this.layout.active) {
  58. // 标记selected
  59. this.layout.children.forEach((item, index) => {
  60. if (index === this._current_idx) {
  61. item.getChildByName("selected").active = true;
  62. } else {
  63. item.getChildByName("selected").active = false;
  64. }
  65. })
  66. }
  67. }
  68. }