Dynamic height for shapes in SwiftUI

Viewed 2858

Here's a minimal, reproducible example of what I want to do.

I have an array of paragraphs.

var notes = [
    "One line paragraph",
    "This is a small paragraph. This is a small paragraph. This is a small paragraph. This is a small paragraph.",
    "This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph."
]

This is how I want to display this: enter image description here

Here's my code.

struct ContentView: View {
    var notes = [
        "One line paragraph",
        "This is a small paragraph. This is a small paragraph. This is a small paragraph. This is a small paragraph.",
        "This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph."
    ]

    var body: some View {
        VStack(alignment: .leading) {
            ForEach(self.notes, id: \.self) {note in
                HStack {
                    Capsule()
                        .fill(Color.blue)
                        .frame(width: 4.5)

                    Text(note)
                    .lineLimit(nil)
                }
                .padding()
            }

        }
    }
}

This is the output I got: enter image description here

I even tried adding a Spacer() to the bottom of the VStack (after the ForEach) but the output is still same.

What I want to know is how to change the height of those blue vertical bars to the height of their respective paragraphs like in the first screenshot.

1 Answers

Here is possible approach. Tested with Xcode 11.4 / iOS 13.4

demo

var body: some View {
    VStack(alignment: .leading) {
        ForEach(self.notes, id: \.self) {note in
            HStack {
                Text(note)
                    .padding(.leading)
            }
            .overlay(Capsule()       // also can be .background
                        .fill(Color.blue)
                        .frame(width: 4.5), alignment: .leading)
            .padding()
        }
    }
}
Related