Skip to content

Instantly share code, notes, and snippets.

@karljj1
Created January 15, 2021 18:39
Show Gist options
  • Save karljj1/fb2d61a9ea72c6cd9eff705220810d94 to your computer and use it in GitHub Desktop.
Save karljj1/fb2d61a9ea72c6cd9eff705220810d94 to your computer and use it in GitHub Desktop.
An example of how a UI Toolkit TextField Suggestion field could be created
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
public class TextEditorWindow : EditorWindow
{
VisualElement m_Suggestion;
TextField m_TextField;
[MenuItem("Test/Window")]
static void ShowWn()
{
CreateWindow<TextEditorWindow>();
}
private void OnEnable()
{
m_TextField = new TextField();
m_TextField.RegisterValueChangedCallback(TextChange);
rootVisualElement.Add(m_TextField);
rootVisualElement.Add(new Label("Some Label"));
rootVisualElement.Add(new Button { text = "Some Button" });
}
void TextChange(ChangeEvent<string> evt)
{
if (m_Suggestion == null)
{
m_Suggestion = new VisualElement
{
style =
{
backgroundColor = new Color(0.3f, 0.3f, 0.3f),
borderTopColor = Color.black,
borderBottomColor = Color.black,
borderLeftColor = Color.black,
borderRightColor = Color.black,
borderLeftWidth = 1,
borderBottomWidth = 1,
borderRightWidth = 1,
borderTopWidth = 1,
position = Position.Absolute,
}
};
rootVisualElement.Add(m_Suggestion);
}
m_Suggestion.Clear();
for (int i = 0; i < Random.Range(5, 10); ++i)
{
var text = System.Guid.NewGuid().ToString();
var label = new Label(text);
label.RegisterCallback<MouseDownEvent>(evt =>
{
m_TextField.SetValueWithoutNotify(text);
m_Suggestion.RemoveFromHierarchy();
m_Suggestion = null;
});
m_Suggestion.Add(label);
}
m_Suggestion.style.top = m_TextField.layout.yMax;
}
}
@karljj1
Copy link
Author

karljj1 commented Jan 15, 2021

Jan-15-2021 18-37-43

@karljj1
Copy link
Author

karljj1 commented Jan 15, 2021

You could do more like change focus when you press up/down with the mouse and press return etc
This version needs you to click on the text

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment