HKMBFZ/Assets/Scripts/Szz_Scripts/UI/CustomUI/CustomTMPInputField.cs

106 lines
2.2 KiB
C#

using UnityEngine;
using TMPro;
using UnityEngine.EventSystems;
using System.Collections;
public class CustomTMPInputField : TMP_InputField
{
private bool forceFocus = false;
protected override void Awake()
{
base.Awake();
}
public override void OnPointerClick(PointerEventData eventData)
{
base.OnPointerClick(eventData);
if (!forceFocus)
{
Activate();
}
}
public override void OnDeselect(BaseEventData eventData)
{
if (forceFocus)
{
StartCoroutine(DelayedSelect());
}
else
{
base.OnDeselect(eventData);
}
}
private IEnumerator DelayedSelect()
{
yield return null;
if (EventSystem.current != null && EventSystem.current.currentSelectedGameObject != gameObject)
{
EventSystem.current.SetSelectedGameObject(gameObject);
// TMP 原生激活输入框,显示光标
ActivateInputField();
// 强制同步 placeholder 状态
ForceRefresh();
}
}
/// <summary>
/// 激活并保持焦点
/// </summary>
public void Activate()
{
forceFocus = true;
StartCoroutine(DelayedSelect());
}
/// <summary>
/// 主动关闭焦点
/// </summary>
public void Deactivate()
{
forceFocus = false;
DeactivateInputField();
if (EventSystem.current != null && EventSystem.current.currentSelectedGameObject == gameObject)
EventSystem.current.SetSelectedGameObject(null);
ForceRefresh();
}
/// <summary>
/// 是否有焦点
/// </summary>
public bool HasFocus()
{
return forceFocus && isFocused;
}
/// <summary>
/// 手动切换到另一个输入框
/// </summary>
public void SwitchFocus(CustomTMPInputField nextField)
{
if (nextField == null) return;
ForceRefresh();
Deactivate();
nextField.Activate();
nextField.ForceRefresh();
}
/// <summary>
/// 强制刷新 placeholder 状态
/// </summary>
public void ForceRefresh()
{
if (placeholder != null)
placeholder.gameObject.SetActive(string.IsNullOrEmpty(text) && !isFocused);
}
}