swiftuiswiftui-view

How to stop a View from automatically expanding to infinity?


I would like to underline a Text View using a Rectangle that has the same width as the Text View.

Here is my attempt:

struct Title: View {
    var body: some View {
        VStack {
            Text("Statistics")
            Rectangle()
            .foregroundColor(.red)
            .frame(height: (5.0))
        }
    }

}

But I get this result:

enter image description here

But I want this result:

enter image description here

Is there a way to create an extension to Text that could be applied to the Rectangle like this:

struct Title: View {

    var body: some View {
        VStack {
            Text("Statistics")
            Rectangle()
            .foregroundColor(.red)
            .frame(width: Text.width, height: (5.0))
        }
    }

}

Using such an extension, the text would be dynamically underlined with a Rectangle of correct width.

I have already referred this question but its apparently not be the same issue.


Solution

  • Just specify that container has fixed size and it will tight to content, like

    demo

    var body: some View {
        VStack {
            Text("Statistics")
            Rectangle()
            .foregroundColor(.red)
            .frame(height: (5.0))
        }.fixedSize()              // << here !!
    }