代码之家  ›  专栏  ›  技术社区  ›  Aaron Bratcher

SwiftUI框架宽度问题和点击手势不起作用

  •  0
  • Aaron Bratcher  · 技术社区  · 3 年前

    我想在标题下面画一个矩形,这个矩形应该与文本宽度相同。

    首先,我创建一个带下划线的文本,如下所示:

    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

    所以我想知道是否有可能绑定文本宽度,并将其应用于矩形,方法如下:

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

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

    我尝试了很多选择,但我找不到怎么做。我也检查过了 this question 但这似乎不是同一个问题。

    0 回复  |  直到 5 年前
        1
  •  28
  •   Asperi    2 年前

    只需指定容器有固定的大小,它就会与内容紧密相连,比如

    demo

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

    backup