2025-09-08 17:37:12 +08:00

59 lines
2.2 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using UnityEngine;
using UnityEngine.UI;
using static UnityEngine.Rendering.DebugUI;
[RequireComponent(typeof(InputField))]
public class AutoExpandInputField : MonoBehaviour
{
private InputField inputField;
private Text inputText;
//private ContentSizeFitter contentSizeFitter;
//private LayoutElement layoutElement;
private RectTransform rectTransform;
private void Awake()
{
inputField = GetComponent<InputField>();
inputText = inputField.textComponent;
//contentSizeFitter = GetComponent<ContentSizeFitter>();
//layoutElement = GetComponent<LayoutElement>();
rectTransform = GetComponent<RectTransform>();
// 监听输入内容变化事件,当输入框文字改变时触发扩容检查
inputField.onValueChanged.AddListener(OnValueChanged);
}
//private void OnEnable()
//{
// layoutElement.preferredHeight = layoutElement.minHeight;
// rectTransform.anchoredPosition = new Vector2 (-158.9837f, -67.5f);
//}
//private void Update()
//{
// Canvas.ForceUpdateCanvases();
// // 获取文本实际需要的高度
// float requiredHeight = inputText.flexibleHeight;
// // 若有LayoutElement组件利用其最小高度限制同时更新首选高度
// if (layoutElement != null)
// {
// // 确保计算出的高度不小于设置的最小高度
// requiredHeight = Mathf.Max(requiredHeight, layoutElement.minHeight);
// layoutElement.flexibleHeight = requiredHeight;
// }
// else
// {
// // 没有LayoutElement时直接基于ContentSizeFitter和文本需求调整高度实际项目中一般都会有LayoutElement配合这里做兼容处理
// rectTransform.sizeDelta = new Vector2(rectTransform.sizeDelta.x, requiredHeight);
// }
// // 触发布局重新计算让ContentSizeFitter等生效更新实际显示
// if (contentSizeFitter != null)
// {
// contentSizeFitter.SetLayoutVertical();
// }
//}
void OnValueChanged(string text)
{
// 计算文本内容的高度
int preferredHeight = Mathf.CeilToInt(inputField.textComponent.preferredHeight) + 20; // 20是上下边距
rectTransform.sizeDelta = new Vector2(rectTransform.sizeDelta.x, preferredHeight);
}
}