gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 15:54:34 26 4
gpt4 key购买 nike

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

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

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com