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

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

问题描述

我想用一个矩形给标题加下划线,该矩形的宽度应与文本相同.

首先我创建一个下划线文本如下:

struct 标题:查看 {var主体:一些视图{虚拟堆栈{文本(统计")长方形().foregroundColor(.red).frame(高度:(5.0))}}}

所以我得到以下结果:

现在我想得到这个结果:

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

struct 标题:查看 {var主体:一些视图{虚拟堆栈{文本(统计")长方形().foregroundColor(.red).frame(width: Text.width, height: (5.0))}}}

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

我尝试了很多选择,但我找不到如何去做.我还检查了

var body: some View {虚拟堆栈{文本(统计")长方形().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天全站免登陆