0

I want to make a UI that loads an array of strings into a scrollable horizontal stack. The texts however should have a max width of 100, and expand to be multiline to fill the space. This works, however the text is cut off and the horizontal ScrollView is only allowing the height for one line of text.

How do I let the ScrollView expand vertically to whatever the largest text in the stack is?

I want to have a control right above the stack, so setting the height to .infinity isn't a solution, and preferably don't want to have to work with GeometryReader.

My code so far:

VStack {
    Capsule()
        .foregroundColor(.black.opacity(0.5))
        .frame(width: 48, height: 2)
    ScrollView(.horizontal, showsIndicators: false) {
        HStack {
            ForEach(chats, id: \.self) { chat in
                Text(chat)
            }
            .fixedSize(horizontal: false, vertical: true)
            .frame(maxWidth: 100)
        }
    }
}

The result:

result

Priva28
  • 327
  • 1
  • 10

1 Answers1

0

Change .frame(maxWidth: 100) to .frame(width: 100). You'll then need to put a maxHeight on your HStack lest it grow too tall.

VStack {
    Capsule()
        .foregroundColor(.black.opacity(0.5))
        .frame(width: 48, height: 2)
    ScrollView(.horizontal, showsIndicators: false) {
        HStack(alignment: .top) {
            ForEach(chats, id: \.self) { chat in
                Text(chat)
                    .frame(width: 100)
            }
        }
        .frame(maxHeight: 200, alignment: .top)
    }
}

Result:

Three columns of text. Each is limited to 100 points wide and is truncated after 7 lines.

rob mayoff
  • 375,296
  • 67
  • 796
  • 848
  • Thanks! This is probably the best option for now, but the only issue then is that text smaller than 100px ends up being larger than it should. Preferably I want everything to be able to shrink to fit to it's size but looks like I'm going to have to work out some more complex way of doing so. – Priva28 Feb 03 '23 at 04:31
  • Do your users send a lot of extremely short chats like “l” and ”!”? – rob mayoff Feb 03 '23 at 05:10