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:
But I want this result:
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.
Just specify that container has fixed size and it will tight to content, like
var body: some View {
VStack {
Text("Statistics")
Rectangle()
.foregroundColor(.red)
.frame(height: (5.0))
}.fixedSize() // << here !!
}