David
David

Reputation: 598

Adding horizontal ScrollView to code-generated GridLayout

I have this sample code that works as I want:

<ScrollView orientation="horizontal">
  <GridLayout columns="*,*,*,*,*,*" >
    <Label class="gridlabel" col="0" text="Monday" />
    <Label class="gridlabel" col="1" text="Tuesday" />
    <Label class="gridlabel" col="2" text="Wednesday" />
    <Label class="gridlabel" col="3" text="Thursday" />
    <Label class="gridlabel" col="4" text="Friday" />
    <Label class="gridlabel" col="5" text="Saturday" />
  </GridLayout>
</ScrollView>  

That is, the labels within the GridLayout scroll horizontally.

I have a component that generates a GridLayout, and now I need to wrap that in a horizontal ScrollView.

That is, I for each label:

  let label = new Label();

  // Add tap event handler for each tab
  label.on("tap", function () {
    onTabTap(label, "tabTap");
  }.bind(label));

  label.id = key;
  label.text = key;
  label.class = "gridtab";
  this.addColumn(new ItemSpec(1, GridUnitType.STAR));
  GridLayout.setColumn(label, i);
  GridLayout.setRow(label, 0);
  this.addChild(label);

But when I try to add the ScrollView, I get errors. If I try to add the labels to the ScrollView, such as scrollView.addChild(label) (where scrollView is an instance of ScrollView), I get "scrollView.addChild is not a function". (See this similar SO post). If, as suggested in the mentioned post, I use scrollView.content = this; then I get the error, Error: View already has a parent.

So, the question is, from code, how do I replicate the hierarchy from my sample xml? That is, how can I wrap the generated GridLayout in a horizontal ScrollView?

Edit 7/17/2020

Upon reflection, I don't think this can work given my component's current design. That is, it subclasses GridLayout, and I want the generated GridLayout to be wrapped by a ScrollView, but that would be external to the content generated by the component, yes? It almost seems I'd need to subclasss ScrollView, and then generate the GridLayout within.

Upvotes: 0

Views: 68

Answers (1)

David
David

Reputation: 598

So, I was ultimately able to resolve this by subclassing StackLayout, then within the StackLayout adding a ScrollView, and within the ScrollView adding the GridLayout. The "magic" is:

scroll.content = grid;
this.addChild(scroll);

Where scroll is the ScrollView instance, and grid is the GridLayout instance.

Then, after spending a day on this I found I didn't actually need horizontal scrolling after all, but at least I know what to do should the need arise.

Upvotes: 1

Related Questions