我想用一个与文本具有相同宽度的矩形在标题下划线。
首先,我创建一个带下划线的文本,如下所示:
struct Title: View {
var body: some View {
VStack {
Text("Statistics")
Rectangle()
.foregroundColor(.red)
.frame(height: (5.0))
}
}
}
Run Code Online (Sandbox Code Playgroud)
所以我得到以下结果:
现在我想得到这个结果:
所以我想知道是否可以通过编写以下内容来绑定文本宽度并将其应用于矩形:
struct Title: View {
var body: some View {
VStack {
Text("Statistics")
Rectangle()
.foregroundColor(.red)
.frame(width: Text.width, height: (5.0))
}
}
}
Run Code Online (Sandbox Code Playgroud)
通过这样做,我可以更改文本,并且它会以正确的宽度动态加下划线。
我尝试了很多选择,但我找不到如何去做。我也检查了这个问题,但似乎不是同一个问题。
Asp*_*eri 24
只需指定容器具有固定大小并且它会紧缩内容,例如
var body: some View {
VStack {
Text("Statistics")
Rectangle()
.foregroundColor(.red)
.frame(height: (5.0))
}.fixedSize() // << here !!
}
Run Code Online (Sandbox Code Playgroud)