How to get Text width with SwiftUI?
Asked Answered
F

1

10

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.

Frieda answered 27/3, 2020 at 14:55 Comment(0)
C
41

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 !!
}
Cameron answered 27/3, 2020 at 14:59 Comment(1)
Thank you so much, this answer has helped me with with a weird resize issue I was facing with .sheet! For cross-referencing: #76525561Borate

© 2022 - 2024 — McMap. All rights reserved.