【问题标题】:How to get Text width with SwiftUI?如何使用 SwiftUI 获取文本宽度?
【发布时间】:2020-03-27 14:55:26
【问题描述】:

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

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

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

}

所以我得到以下结果:

现在我想得到这个结果:

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

struct Title: View {

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

}

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

我尝试了很多选项,但找不到方法。我还检查了this question,但这似乎不是同一个问题。

【问题讨论】:

    标签: ios xcode swiftui


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-09
      • 2019-12-25
      • 1970-01-01
      • 1970-01-01
      • 2020-01-03
      • 1970-01-01
      相关资源
      最近更新 更多