unity 使用UI上的数字按钮,给text添加数字,并且显示光标,删除光标前数字,

发布于:2024-11-28 ⋅ 阅读:(205) ⋅ 点赞:(0)

今天有个需求,输入身份证,但是不用键盘,要点击按钮输入数字,并且可以控制光标,
1、数字按钮:点击后text添加数字内容
2、删除按钮:删除光标前的一个字符
3、左箭头:移动光标向左移动
在这里插入图片描述

text内容显示光标并控制

  public void InitNumberButton()
  {
  //number是这些按钮的父物体
    Button[] buttons=  number.GetComponentsInChildren<Button>();
      StringBuilder builder=new StringBuilder();
   
  
      foreach (Button button in buttons)
      {
          if(button.name=="Delect")
          {
              button.onClick.AddListener(() => {

                  DeleteCharacterBeforeCursor();
              });
          }
          else if(button.name=="zuo")
          {
              button.onClick.AddListener(() => {
                  MoveCursorLeft();


              });
          }
          else
          {
              button.onClick.AddListener(() => {
                  //currentText = builder.Append(button.name).ToString();
                  characterToInsert=button.name;
                  // identityInput.text = builder.Append(button.name).ToString();
                  InsertCharacter();
              });
          }
      }
  }
  private string currentText = "";  // 当前的文本内容
  private int cursorPosition = 0;  // 光标的位置(索引)
   private string characterToInsert = "A";
  // 更新显示文本(包括光标位置)
  void UpdateDisplayText()
  {
      // 在光标位置插入特殊符号来模拟光标
      string textWithCursor = currentText.Insert(cursorPosition, "|");
      card.text = textWithCursor;
  }

  // 插入字符并将光标移到字符后面
  void InsertCharacter()
  {
      // 在光标位置插入字符
      currentText = currentText.Insert(cursorPosition, characterToInsert);

      // 将光标移到插入字符后面
      cursorPosition++;

      // 更新显示
      UpdateDisplayText();
  }

  // 控制光标向左移动
  void MoveCursorLeft()
  {
      // 如果光标没有移到最左边,则移动光标
      if (cursorPosition > 0)
      {
          cursorPosition--;
      }

      // 更新显示
      UpdateDisplayText();
  }

  // 删除光标前的一个字符
  void DeleteCharacterBeforeCursor()
  {
      // 如果光标不在文本开头,则删除光标前的字符
      if (cursorPosition > 0)
      {
          // 删除光标前的字符
          currentText = currentText.Remove(cursorPosition - 1, 1);

          // 将光标位置移动到删除的位置
          cursorPosition--;

          // 更新显示
          UpdateDisplayText();
      }
  }


网站公告

今日签到

点亮在社区的每一天
去签到