Textfield placeholder

How can I add placeholder to Textfield?
Just filling the field text in the inspector does not suit me.

Apparently, not yet, but it’s on Unity’s todo list: Is there no "placeholder" text property for TextField()?

I would try adding a new Label as a child of the TextField and/or experiment with absolute positioning.

1 Like

Here’s my implementation:

public static void SetPlaceholderText(this TextField textField, string placeholder)
{
    string placeholderClass = TextField.ussClassName + "__placeholder";

    onFocusOut();
    textField.RegisterCallback<FocusInEvent>(evt => onFocusIn());
    textField.RegisterCallback<FocusOutEvent>(evt => onFocusOut());

    void onFocusIn()
    {
        if (textField.ClassListContains(placeholderClass))
        {
            textField.value = string.Empty;
            textField.RemoveFromClassList(placeholderClass);
        }
    }

    void onFocusOut()
    {
        if (string.IsNullOrEmpty(textField.text))
        {
            textField.SetValueWithoutNotify(placeholder);
            textField.AddToClassList(placeholderClass);
        }
    }
}

Usage:

myTextField.SetPlaceholderText("Placeholder text");

You can also customize its appearance in USS:

.unity-text-field__placeholder > .unity-base-text-field__input {
    color: #969696
}
2 Likes

This is my solution.

  1. Add a Label to the TextField and set the ‘Picking Mode’ to ‘Ignore’
  2. Customize the Label with USS
  3. Bind the ‘ChangeEvent’ to the Input element

1+2.) Add a Label to the TextField and customize the style

3.) Add the code to made the placeholder working

That’s it.

I have this done with Unity 2021.3 LTS.

Note: If you set the placeholder.text' after the input.RegisterCallback`, then if on the first time the placeholder not visible. Why? It will a event called with the the signed text before. I’m not sure, but could be a bug in Unity.