9

I would like to underline a title with a rectangle that should have the same width as the Text.

First I create an underlined text as below:

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

}

So I get the following result:

enter image description here

Now I want to get this result:

enter image description here

So I would like to know if it's possible to bind Text width and apply it to Rectangle by writing something like :

struct Title: View {

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

}

By doing so, I could change text and it will be dynamically underlined with correct width.

I tried many options but I can't find how to do it. I also checked this question but it's seems to not be the same issue.

nelson PARRILLA
  • 498
  • 1
  • 6
  • 17

1 Answers1

39

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 !!
}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Asperi
  • 228,894
  • 20
  • 464
  • 690
  • Thank you so much, this answer has helped me with with a weird resize issue I was facing with `.sheet`! For cross-referencing: https://stackoverflow.com/questions/76525061/swiftui-sheet-view-resizing-issue-testing-on-macos/76526168#76526168 – LostBalloon Jun 21 '23 at 18:30