如何使用SwiftUI获得文本宽度? [英] How to get Text width with SwiftUI?

查看:111
本文介绍了如何使用SwiftUI获得文本宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在矩形的标题下划线,该矩形的宽度应与文本的宽度相同.

首先,我创建一个带下划线的文本,如下所示:

  struct标题:查看{var body:some View {VStack {文字(统计信息")长方形().foregroundColor(.red).frame(高度:(5.0))}}} 

所以我得到以下结果:

现在我想得到这个结果:

所以我想知道是否可以通过写类似以下内容来绑定文本宽度并将其应用于Rectangle:

  struct标题:查看{var body:some View {VStack {文字(统计信息")长方形().foregroundColor(.red).frame(width:Text.width,height:(5.0))}}} 

这样做,我可以更改文本,并以正确的宽度动态加下划线.

我尝试了很多选择,但找不到方法.我还检查了

 变量主体:某些视图{VStack {文字(统计信息")长方形().foregroundColor(.red).frame(高度:(5.0))} .fixedSize()//<<这里 !!} 

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:

Now I want to get this result:

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.

解决方案

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

这篇关于如何使用SwiftUI获得文本宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆