Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
527 views
in Technique[技术] by (71.8m points)

ios - How to get Text width with 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...