Keep text from going off the top of the widget

How do I prevent text from getting pushed up passed the top of the widget when there are too many items in the list widget?


let w = new ListWidget()
let h = w.addText("Header")
h.font = Font.blackSystemFont(12)

for (var i = 0; i < 25; i++) {
  w.addText("item " + i)
}
w.addSpacer()
w.presentLarge()

If you reduce this number to only 5 or so the header is at the top all nice and neat, but add more and the items get a little too pushy and the header is no longer present. What’s the trick I’m missing here?

I don’t have an answer to your question specifically, but maybe try setting the text’s minimumScaleFactor to make it auto-fit the content.

for (var i = 0; i < 25; i++) {
  let item = w.addText("item " + i)
  item.minimumScaleFactor = 0.7
}

Interesting. I wonder if there’s a way to not push up but only push down.

You can move the w.addSpacer() before text list to push them down.

That only works until I have fewer items then it’s pushed to the center which is not the desired outcome.

Do you need to style each text item? If not, maybe add them as a single text in a stack.

let w = new ListWidget()
let h = w.addText("Header")
h.font = Font.blackSystemFont(12)

w.addSpacer()

let items = []
for (var i = 0; i < 25; i++) {
  items.push(`item ${i}`)
}

let s = w.addStack()
s.layoutVertically()
s.bottomAlignContent()
s.addText(items.join("\n"))

w.presentLarge()

Or, maybe you can set a threshold of the maximum number of items that you want to show. Then only add up to that number of items.

1 Like

Yep. That’s what I ended up doing. It works okay for now. I can’t do the single stack because each item actually is made up of three pieces of text on their own with varying colors.

Thanks!