[SOLVED] ToolbarToggle with text="" not working

I am using ToolbarToggle buttons with images instead of text labels, but for some reason they won’t respond to clicks.

This is my UXML:

<editor:ToolbarToggle name="MyToggleButton" text="">
    <Image style="background-image: url('img.png');" />
</editor:ToolbarToggle>

When clicked, the toggle button color flashes, indicating that it received the click, but then it does not remain in its toggled state, and also does not trigger RegisterValueChangedCallback.

Changing the attribute to text=“anything” makes the toggle button behave as expected (but hiding my pretty image). I have tried setting the image’s PickingMode to Ignore, but it doesn’t help.

Is this expected behaviour or a bug?

edit: Using Unity 2019.3b12.

The ToolbarToggle is a reskinned Toggle which has inside an “input” element. In a normal Toggle, this element is the one that contains the checkbox and the text, but the ToolbarToggle hides the checkbox and just uses the text (a Label element). This means that it’s that Label element that handles the clicks, not the ToolbarToggle element itself.

A couple of suggestions:

  1. Only use Image if you really want the image file to drive the size of your element. In most cases, it should be the UI that drives its own sizes, not the image assets. The Image element is really just meant for things like an image preview viewport, not for icons in buttons, and it doesn’t use the background-image style to do this - it has its own imageSource property that you can only set in C#. Instead, use an empty VisualElement with a background-image style (as you already do).
  2. You can make your icon element above float behind the Input element of the ToolbarToggle (which is a sibling element) by setting this style:
position: absolute;
left: 0;
top: 0;
right: 0;
left: 0;

You can then continue setting the text property of your ToolbarToggle.
3. Use the UIElements Debugger (Windows > Analysis) to see the exact live hierarchy of your elements and see why your elements might not be visible.

Thanks! After some experimentation, I decided to keep the inner tag to make the image scale properly, but using your suggested positioning attributes to make it float behind the input element.

So now the ToolbarToggle has a fixed width and text=" " which makes it clickable and all works well (except the uxml and uss are perhaps a bit ugly).

Just to confirm, the Image element will not do anything for you if you assign the image asset via background-image style. You have to set the special Image.image source property in C#. It will also not work with the above styles suggested since both the Image and the layout system will try to set the size of the Image element and you’ll have a race. Image really only works when it uses position: relative. But…if it works for you then no need to change!