84 lines
2.2 KiB
C#
84 lines
2.2 KiB
C#
using TMPro;
|
||
using UnityEngine;
|
||
|
||
public static class TMPInputSimulator
|
||
{
|
||
/// <summary>
|
||
/// 模拟输入字符或字符串
|
||
/// </summary>
|
||
public static void InsertText(CustomTMPInputField field, string textToInsert)
|
||
{
|
||
if (field == null) return;
|
||
|
||
int pos = field.caretPosition;
|
||
string currentText = field.text;
|
||
|
||
// 插入文字
|
||
field.text = currentText.Substring(0, pos) + textToInsert + currentText.Substring(pos);
|
||
field.caretPosition = pos + textToInsert.Length;
|
||
|
||
// 刷新显示
|
||
field.ForceLabelUpdate();
|
||
field.ForceRefresh();
|
||
|
||
// 触发 onValueChanged
|
||
field.onValueChanged?.Invoke(field.text);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 模拟删除光标前的字符(Backspace)
|
||
/// </summary>
|
||
public static void Backspace(CustomTMPInputField field)
|
||
{
|
||
if (field == null) return;
|
||
int pos = field.caretPosition;
|
||
|
||
if (pos <= 0) return;
|
||
|
||
string currentText = field.text;
|
||
field.text = currentText.Substring(0, pos - 1) + currentText.Substring(pos);
|
||
field.caretPosition = pos - 1;
|
||
|
||
field.ForceLabelUpdate();
|
||
field.ForceRefresh();
|
||
field.onValueChanged?.Invoke(field.text);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 模拟删除光标后的字符(Delete)
|
||
/// </summary>
|
||
public static void Delete(CustomTMPInputField field)
|
||
{
|
||
if (field == null) return;
|
||
int pos = field.caretPosition;
|
||
string currentText = field.text;
|
||
|
||
if (pos >= currentText.Length) return;
|
||
|
||
field.text = currentText.Substring(0, pos) + currentText.Substring(pos + 1);
|
||
field.caretPosition = pos;
|
||
|
||
field.ForceLabelUpdate();
|
||
field.ForceRefresh();
|
||
field.onValueChanged?.Invoke(field.text);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 移动光标到指定位置
|
||
/// </summary>
|
||
public static void SetCaretPosition(CustomTMPInputField field, int position)
|
||
{
|
||
if (field == null) return;
|
||
field.caretPosition = Mathf.Clamp(position, 0, field.text.Length);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 移动光标到文本末尾
|
||
/// </summary>
|
||
public static void MoveCaretToEnd(CustomTMPInputField field)
|
||
{
|
||
if (field == null) return;
|
||
field.caretPosition = field.text.Length;
|
||
}
|
||
}
|