ios - 如何使用 SwiftUI 获取文本宽度?

标签 ios xcode swiftui

我想用一个应该与文本宽度相同的矩形在标题下划线。

首先,我创建如下带下划线的文本:

struct Title: View {
    var body: some View {
        VStack {
            Text("Statistics")
            Rectangle()
            .foregroundColor(.red)
            .frame(height: (5.0))
        }
    }

}

所以我得到以下结果:

enter image description here

现在我想得到这个结果:

enter image description here

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

    var body: some View {
        VStack {
            Text("Statistics")
            Rectangle()
            .foregroundColor(.red)
            .frame(width: Text.width, height: (5.0))
        }
    }

}

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

我尝试了很多选择,但我找不到如何去做。我还检查了this question但这似乎不是同一个问题。

最佳答案

只需指定该容器具有固定大小,它将紧贴内容,例如
demo

var body: some View {
    VStack {
        Text("Statistics")
        Rectangle()
        .foregroundColor(.red)
        .frame(height: (5.0))
    }.fixedSize()              // << here !!
}
backup

关于ios - 如何使用 SwiftUI 获取文本宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60888495/

相关文章:

ios - UIGraphicsBeginImageContextWithOptions - 返回的图像有不需要的边框

ios 转场 "cancel"

ios - 在不覆盖自定义更改的情况下更新 GitHub iOS SDK

ios - 按字母顺序获取联系人

objective-c - 在 objective-c 中比较 NSUInteger 和 int(例如 5)的最快方法是什么?

ios - 为什么我的 Xcode 知道项目目录应该有这些文件?

ios - @AppStorage 变量上的“调用初始化程序时没有完全匹配”错误?

ios - 使用 @State 变量属性作为绑定(bind)

swift - 有没有办法在 SwiftUI View 和与其间接相关的类之间设置一个全局变量?

ios - get "Undefined symbols for architecture i386:"尝试获取常量