Skip to content

Instantly share code, notes, and snippets.

@thebeardphantom
Last active January 30, 2022 23:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thebeardphantom/bb841ea246185c57dc2e642069e29aae to your computer and use it in GitHub Desktop.
Save thebeardphantom/bb841ea246185c57dc2e642069e29aae to your computer and use it in GitHub Desktop.
A very simple wrapper around IMGUI's AdvancedDropdown for UI Toolkit.
public class AdvancedDropdownField : DropdownField
{
#region Types
private class SimpleAdvancedDropdown : AdvancedDropdown
{
#region Fields
private readonly DropdownField _dropdownField;
private readonly string _title;
private readonly List<string> _choices;
#endregion
#region Constructors
public SimpleAdvancedDropdown(DropdownField dropdownField, string title, List<string> choices) : base(
new AdvancedDropdownState())
{
_dropdownField = dropdownField;
_title = title;
_choices = choices;
}
#endregion
#region Methods
/// <inheritdoc />
protected override void ItemSelected(AdvancedDropdownItem item)
{
_dropdownField.index = item.id;
_dropdownField.tooltip = item.name;
}
/// <inheritdoc />
protected override AdvancedDropdownItem BuildRoot()
{
var root = new AdvancedDropdownItem(_title)
{
id = -1
};
for (var i = 0; i < _choices.Count; i++)
{
var choice = _choices[i];
root.AddChild(
new AdvancedDropdownItem(choice)
{
id = i
});
}
return root;
}
#endregion
}
#endregion
#region Fields
private readonly SimpleAdvancedDropdown _advancedDropdown;
#endregion
#region Constructors
public AdvancedDropdownField(string dropdownTitle, List<string> choices, int index) : base(dropdownTitle, choices, index)
{
_advancedDropdown = new SimpleAdvancedDropdown(this, dropdownTitle, choices);
tooltip = choices[index];
RegisterCallback<PointerDownEvent>(OnPointerDown, TrickleDown.TrickleDown);
AddToClassList(alignedFieldUssClassName);
}
#endregion
#region Methods
private void OnPointerDown(PointerDownEvent evt)
{
var popup = this[1];
if (evt.button != 0 || !popup.worldBound.Contains(evt.position))
{
return;
}
evt.StopImmediatePropagation();
_advancedDropdown.Show(new Rect(evt.position, Vector2.zero));
}
#endregion
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment