Two Text inside a ScrollView that Fit to the content of the Texts

137 Views Asked by At

I have two Text in a VStack. Both texts can grow to an unlimited amount of lines. I want that if the text grows more than the screen I can scroll and see all the content.

Mi first approach:

var body: some View {
    VStack(alignment: .center, spacing: 0) {

        VStack(alignment: .leading, spacing: 8) {
            Text(title)
                .font(.title)
            Text(subtitle)
                .font(.subheadline)
        }
            .frame(maxWidth: .infinity)
            .background(Color.orange)
            .padding(.top, 24)
            .padding(.horizontal, 24)

        Button(buttonTitle) { }
            .frame(maxWidth: .infinity, minHeight: 50)
            .background(Color.red)
            .foregroundColor(.white)
            .padding(.all, 24)

    }.background(Color.gray)
        .frame(maxWidth: UIScreen.main.bounds.size.width - 20)
}

Result:

enter image description here

Of course there is no scroll... so I added a ScrollView:

var body: some View {
    VStack(alignment: .center, spacing: 0) {

        ScrollView {
            VStack(alignment: .leading, spacing: 8) {
                Text(title)
                    .font(.title)
                Text(subtitle)
                    .font(.subheadline)
            }
                .frame(maxWidth: .infinity)
                .background(Color.orange)
                .padding(.top, 24)
                .padding(.horizontal, 24)
        }

        Button(buttonTitle) { }
            .frame(maxWidth: .infinity, minHeight: 50)
            .background(Color.red)
            .foregroundColor(.white)
            .padding(.all, 24)

    }.background(Color.gray)
        .frame(maxWidth: UIScreen.main.bounds.size.width - 20)
}

Result:

enter image description here

It works! But when the text is not enough to fill the whole height of the screen the ScrollView still expands to the whole space available and I want it to wrap the content and "disable" the scrolling capability.

Sample of what I get with little amount of text:

enter image description here

Sample of what I would like to get with little amount of text:

enter image description here

So the question is how can I make the ScrollView to "wrap" the content instead of expanding to the whole height of the parent View?

0

There are 0 best solutions below