Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Text width with SwiftUI?

Tags:

xcode

ios

swiftui

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.

like image 450
nelson PARRILLA Avatar asked Mar 27 '20 14:03

nelson PARRILLA


People also ask

How do I make text full width in SwiftUI?

How to make a SwiftUI view to fill its container width or height. To make a SwiftUI view take all available width, we use . frame() modifier with maxWidth and maxHeight set to . infinity .

How is font width calculated?

A font is often measured in pt (points). Points dictate the height of the lettering. There are approximately 72 (72.272) points in one inch or 2.54 cm. For example, the font size 72 would be about one inch tall, and 36 would be about a half of an inch.

How do I show text in SwiftUI?

Text is displayed in SwiftUI using the Text view. The text can be configured in a number of ways using modifiers such as font, fontweight, padding and background. The default Text can handle multiline text and it can be modified to set how many lines to display or how to truncate the text.


Video Answer


1 Answers

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 !!
}
like image 104
Asperi Avatar answered Oct 28 '22 07:10

Asperi