【问题标题】:How can I horizontally align two text views so that the leading and trailing edges meet in the middle?如何水平对齐两个文本视图,以便前缘和后缘在中间相遇?
【发布时间】:2021-06-16 13:58:15
【问题描述】:

我有两个文本视图。它们水平相邻放置。如何对齐它们,使视图的交汇点也是容器视图的中心,而不管任一字符串有多长?

例如...

这是第一个字符串|第二个字符串。

这里的管道将是容器视图的中心。显然,除非两个字符串的宽度完全相同,否则简单的 HStack 将无法工作。 (旁注:在我的特定用例中,字符串不会太长以至于需要截断或换行,但这可能对其他有此问题的人有用)。

【问题讨论】:

    标签: swiftui


    【解决方案1】:

    您可以在两个 Texts 上使用 .frame(maxWidth: .infinity),这最终会使它们的宽度相等(父级的 50%)。

    struct ContentView : View {
        var body: some View {
            VStack {
                HStack(spacing: 2) {
                    
                    Text("Short")
                        .frame(maxWidth: .infinity, alignment: .trailing)
                        .border(Color.blue)
                    Text("Longer. This is longer text....")
                        .lineLimit(1) // remove/change this if you want it to accommodate multiple lines
                        .frame(maxWidth: .infinity, alignment: .leading)
                        .border(Color.green)
                }
            }
        }
    }
    
    

    您可以根据自己的需要使用alignment。当然,边框只是用来调试的。

    【讨论】:

      【解决方案2】:

      为保证管道两侧等宽,可以使用2个Spacer()s。

      HStack {
          Spacer()
          Divider()
          Spacer()
      }
      

      然后,您可以在每个Spacer() 上添加overlay 文本。

      struct ContentView: View {
          var body: some View {
              HStack {
                  Spacer()
                  .overlay(
                      Text("Hi! This text is in multiple lines. Cool, right?")
                          .fixedSize(horizontal: false, vertical: true) /// allow text wrap
                          .multilineTextAlignment(.trailing) /// align text to right when there are multiple lines
                          .frame(maxWidth: .infinity, alignment: .trailing) /// align text to right when there's 1 line
                  )
                  
                  Divider()
                  
                  Spacer()
                  .overlay(
                      Text("Hello!")
                          .fixedSize(horizontal: false, vertical: true)
                          .multilineTextAlignment(.leading)
                          .frame(maxWidth: .infinity, alignment: .leading)
                  )
              }
          }
      }
      

      结果:

      【讨论】:

        猜你喜欢
        • 2019-12-27
        • 2017-08-30
        • 2021-01-21
        • 2017-09-22
        • 2012-10-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多