Unity UGUI InputField plus slider

Only vertical sliding is considered here, and the same applies to the horizontal direction.

The idea is to put the InputField under the ScrollView and let the InputField serve as the Content of the ScrollRect. Dynamically obtain the height of the input text (InputField.preferredHeight), and then change the RectTransform height of the InputField.

Code reference

using UnityEngine;
using UnityEngine.UI;

public class Test : MonoBehaviour
{
    
    
    
    public InputField inputField;
    private RectTransform inputFieldRectTrans;
    private float originHeight;
    public void Awake()
    {
    
    
        inputFieldRectTrans = inputField.GetComponent<RectTransform>();
        originHeight = inputFieldRectTrans.sizeDelta.y;
        inputField.onValueChanged.AddListener(str =>
        {
    
    
            if (inputField.preferredHeight > originHeight || inputFieldRectTrans.sizeDelta.y >= originHeight)
            {
    
    
                // 加上20是防止高度太小InputField显示Text不全,最上边会被InputField截取一部分,根据实际效果修改该数字
                var newHeight = Mathf.Max(originHeight, inputField.preferredHeight + 20);
                inputFieldRectTrans.sizeDelta = new Vector2(inputFieldRectTrans.sizeDelta.x, newHeight);
            }
        });
    }
}



Guess you like

Origin blog.csdn.net/qq_41225779/article/details/115866777