ListView with different Prefab's

Hello,

How can I create a ListView with multiple and different Prefabs?

For example, I have a List with different cells, one for coins, one for diamonds, one for headline and more…
Row 0 → HEADLINE
Row 1 → COINS
Row 2 → COINS
Row 3 → HEADLINE
Row 4 → DIAMONDS
Row 5 → DIAMONDS

I want to show a ListView with all the different Prefabs all-in-one. (The equivalent to iOS UITableView with reusable cells)

How it can be achieved?

Thank you!

I haven’t implemented this, so am just spitballing (ui toolkit team, correct me if there’s a better way), but using this constructor:

public ListView(IList itemsSource, int itemHeight, Func<VisualElement> makeItem, Action<VisualElement, int> bindItem) : this()

it seems like you can customize the cell’s appearance when you’re binding, i.e. branch in bindItem based on the array element your’e binding to, and either add new contents to the cell, or enable/disable elements inside the cell if every variant is added by default? not sure which of these 2 options would be more performant tbh

I think for optimization the ListView will reuse whatever you specified via makeItem. So if you needed a Label for one element type but an Image for another then both need to be added via that and then you use binditem to decide which should be visible. Of course if it is all just labels with different styles then it is much easier as you can simply add or remove style classes during bindItem.

Something like this.

var listView = root.Q<ListView>("the-list");
listView.makeItem = () => new Label();
listView.bindItem = (e, i) =>
{
    var label = e as Label;
    label.text = my_list[i].nameToShow;

    // remove all the classes from the label
    label.RemoveFromClassList("heading");
    label.RemoveFromClassList("list-entry");

    // now add the one you need
    if (my_list[i].type == HeadingType)
    {
        label.AddToClassList("list-heading");
    }
    else
    {
        label.AddToClassList("list-entry");
    }
};