nelson PARRILLA
nelson PARRILLA

Reputation: 703

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.

Upvotes: 11

Views: 13342

Answers (1)

Asperi
Asperi

Reputation: 257711

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 !!
}

Upvotes: 43

Related Questions