PromptItem.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. using System;
  2. using UnityEngine;
  3. using UnityEngine.UI;
  4. public class PromptItem : KeyboardKeydownBtn
  5. {
  6. [HideInInspector]
  7. public Action<string> onPromptItemClick;
  8. [HideInInspector]
  9. public string chineseWord;
  10. public void SetChineseWord(string chineseWord, int index)
  11. {
  12. this.chineseWord = chineseWord;
  13. Text itemText = this.GetComponentInChildren<Text>();
  14. RectTransform itemRect = this.GetComponent<RectTransform>();
  15. float sizeY = itemRect.sizeDelta.y;
  16. if (string.IsNullOrEmpty(chineseWord))
  17. {
  18. itemText.text = "";
  19. SetRectSize(itemRect, 0, sizeY);
  20. return;
  21. }
  22. string displayWord = string.Format("{0}.{1}", (index + 1).ToString(), chineseWord);
  23. int wordLength = KeyboardUtils.CaculateTextLength(displayWord + 20, itemText);
  24. itemText.text = displayWord;
  25. SetRectSize(itemRect, wordLength, sizeY);
  26. this.onClick.RemoveAllListeners();
  27. this.onClick.AddListener(OnPromptItemClick);
  28. }
  29. private void SetRectSize(RectTransform rectTransform, float x, float y)
  30. {
  31. rectTransform.sizeDelta = new Vector2(x, y);
  32. LayoutRebuilder.ForceRebuildLayoutImmediate(rectTransform);
  33. }
  34. private void OnPromptItemClick()
  35. {
  36. onPromptItemClick?.Invoke(this.chineseWord);
  37. }
  38. }