我想用一个应该与文本宽度相同的矩形在标题下划线。
首先,我创建如下带下划线的文本:
struct Title: View {
var body: some View {
VStack {
Text("Statistics")
Rectangle()
.foregroundColor(.red)
.frame(height: (5.0))
}
}
}
所以我得到以下结果:
现在我想得到这个结果:
所以我想知道是否可以通过编写以下内容来绑定(bind)文本宽度并将其应用于矩形:
struct Title: View {
var body: some View {
VStack {
Text("Statistics")
Rectangle()
.foregroundColor(.red)
.frame(width: Text.width, height: (5.0))
}
}
}
通过这样做,我可以更改文本,它会以正确的宽度动态下划线。
我尝试了很多选择,但我找不到如何去做。我还检查了this question但这似乎不是同一个问题。
最佳答案
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/