VerificationCode.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using TMPro;
  4. using UnityEngine;
  5. using UnityEngine.UI;
  6. namespace AppUI.Util.VerifyCode
  7. {
  8. public class VerificationCode : MonoBehaviour
  9. {
  10. [Header("真正输入框")]
  11. public TMP_InputField inputField;
  12. [Header("6个数字文本")]
  13. public TMP_Text[] numberTexts;
  14. [Header("圆圈背景")]
  15. public Image[] circles;
  16. [Header("颜色")]
  17. public Color normalColor = Color.gray;
  18. public Color selectedColor = Color.white;
  19. private void Start()
  20. {
  21. inputField.onValueChanged.AddListener(OnInputChanged);
  22. inputField.characterLimit = 6;
  23. RefreshUI();
  24. // 自动激活输入
  25. inputField.ActivateInputField();
  26. }
  27. private void OnInputChanged(string value)
  28. {
  29. // 只允许数字
  30. string filtered = "";
  31. foreach (char c in value)
  32. {
  33. if (char.IsDigit(c))
  34. {
  35. filtered += c;
  36. }
  37. }
  38. if (filtered != value)
  39. {
  40. inputField.text = filtered;
  41. return;
  42. }
  43. RefreshUI();
  44. // 输入完成
  45. if (filtered.Length == 6)
  46. {
  47. Debug.Log("验证码:" + filtered);
  48. // TODO:
  49. // 提交验证码
  50. }
  51. }
  52. private void RefreshUI()
  53. {
  54. string value = inputField.text;
  55. for (int i = 0; i < numberTexts.Length; i++)
  56. {
  57. if (i < value.Length)
  58. {
  59. numberTexts[i].text = value[i].ToString();
  60. }
  61. else
  62. {
  63. numberTexts[i].text = "";
  64. }
  65. // 当前输入位置高亮
  66. if (i == value.Length && value.Length < 6)
  67. {
  68. circles[i].color = selectedColor;
  69. }
  70. else
  71. {
  72. circles[i].color = normalColor;
  73. }
  74. }
  75. }
  76. // 点击整个区域时激活输入
  77. public void OnClickInputArea()
  78. {
  79. inputField.ActivateInputField();
  80. }
  81. }
  82. }