当前位置: 代码迷 >> 综合 >> Unity InputField输入框自适应文字内容
  详细解决方案

Unity InputField输入框自适应文字内容

热度:94   发布时间:2023-09-21 22:13:41.0

可设置输入框的指定宽度以及高度。效果类似微信的输入框。

LayoutUtility.GetPreferredHeight:返回布局元素的首选高度


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;[RequireComponent(typeof(InputField))]
public class InputContentSize : MonoBehaviour
{public int fontSize = 14;   //输入框的字体大小,InputField的大小会随字体大小改变高度public bool fixedWidth = true;  //是否保持InputField的宽度不变private Vector2 originalSize;   //输入框初始大小int maxHight = 94;//初始输入框高度+每次增加的高度*n 例如初始高度是30 每次增加是16 想最多显示5行就是30+16*4=94 那最大高度值就是94private Text textComponent{get{return this.GetComponent<InputField>().textComponent;}}private RectTransform m_Rect;private RectTransform rectTransform{get{if (m_Rect == null)m_Rect = GetComponent<RectTransform>();return m_Rect;}}private InputField _inputField;public InputField inputField{get{return _inputField ?? (_inputField = this.GetComponent<InputField>());}}protected void Awake(){textComponent.fontSize = fontSize;inputField.placeholder.GetComponent<Text>().fontSize = fontSize;this.originalSize = this.GetComponent<RectTransform>().sizeDelta;inputField.lineType = fixedWidth ? InputField.LineType.MultiLineNewline : InputField.LineType.SingleLine;// rectTransform.SetSizeWithCurrentAnchors((RectTransform.Axis)1, this.originalSize.y);}void OnEnable(){this.inputField.onValueChanged.AddListener(OnValueChanged);}public void OnValueChanged(string v){if (!fixedWidth){rectTransform.SetSizeWithCurrentAnchors((RectTransform.Axis)0, LayoutUtility.GetPreferredWidth(m_Rect));}int i = (int)(LayoutUtility.GetPreferredHeight(m_Rect)) / 16;if(LayoutUtility.GetPreferredHeight(m_Rect) >= maxHight){rectTransform.SetSizeWithCurrentAnchors((RectTransform.Axis)1, maxHight);}else{rectTransform.SetSizeWithCurrentAnchors((RectTransform.Axis)1, i <= 1 ? 30 : 30 + 16 * (i - 1));}//rectTransform.SetSizeWithCurrentAnchors((RectTransform.Axis)1, LayoutUtility.GetPreferredHeight(m_Rect));}}

  相关解决方案