【问题标题】:How to make a view between Spacers always at the center in an HStack?如何在 HStack 中始终位于中心的 Spacers 之间创建视图?
【发布时间】:2020-12-24 13:47:01
【问题描述】:

我想要实现的目标。无论两侧文本宽度的宽度如何,按钮都应始终位于HStack 的中心。

HStack {
    Text("Foooooooo")
    Spacer(minLength: 5)
    Button(action: { }) {
        Text("Bar")
    }
    Spacer()
    Text("Baz")
}
.font(.system(size: 16, weight: .heavy, design: .rounded))
.padding()

我也尝试使用GeometryReader 并在视图中为每个TextButton 设置帧大小但是有两个问题,

  1. GeometryReader 返回的视图将占据父级提供给它的整个视图,而不是实际的内在内容大小,该空间只够TextSpacerButton
  2. 第一个 Text 内的字符串不能左对齐,最后一个 Text 内的字符串也不能右对齐

【问题讨论】:

    标签: ios swift swiftui


    【解决方案1】:

    您想要布局三个灵活但大小相同的元素,但您有三个固定但大小不同的元素。要解决这个问题,请将每个元素放入其自己的灵活堆栈(HStack w/ spacer)中,以便每个元素获得 1/3 的空间。在每个堆栈内,使用 Spacers 对齐。

        HStack {
            // Left stack
            HStack {
                Text("Foooooooo")
                Spacer()
            }
    
            // Center stack. The surrounding Spacers aren't really required in this
            // specific case, but added for consistency and to show how to center.
            HStack {
                Spacer()
                Button(action: { }) {
                    Text("Bar")
                }
                Spacer()
            }
    
            // Right stack
            HStack {
                Spacer()
                Text("Baz")
            }
        }
        .font(.system(size: 16, weight: .heavy, design: .rounded))
        .padding()
    

    【讨论】:

      【解决方案2】:

      这是您的情况的可能方法。使用 Xcode 12 / iOS 14 准备和测试的演示

          HStack {
              Spacer()
                  .overlay(Text("Foooooooo"), alignment: .leading)
      
              Button(action: { }) {
                  Text("Bar")
              }
      
              Spacer()
                  .overlay(Text("Baz"), alignment: .trailing)
          }
          .font(.system(size: 16, weight: .heavy, design: .rounded))
          .padding()
      

      【讨论】:

      • 垫片上的叠加层,非常聪明!
      【解决方案3】:

      这是另一种非常简洁的方法,它使用ZStack 将居中按钮与HStack 与单个Spacer 组合在一起以将标签推到边缘:

      ZStack {
          HStack {
              Text("Foooooooo")
              Spacer()
              Text("Baz")
          }
          Button(action: { }) {
              Text("Bar")
          }
      }
      .font(.system(size: 16, weight: .heavy, design: .rounded))
      .padding()
      

      注意:此解决方案有效您知道您的标签不会侵占您的按钮。 @Asperi 的解决方案导致超长标签被... 截断。 @RobNapier 的解决方案导致超长标签以宽度的 1/3 换行。

      【讨论】:

        猜你喜欢
        • 2021-12-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多