【问题标题】:SwiftUI. How to set shrink behavior for Spacer?斯威夫特用户界面。如何设置 Spacer 的收缩行为?
【发布时间】:2020-03-26 21:02:55
【问题描述】:

如果容器 (VStack) 与底部黑色视图不冲突,如何设置 rgb 视图 (100pt) 之间的默认间距。(如 iPhone 11 Pro Max)。 BUT 如果没有 100p 高度的空间,则会缩小。(如屏幕截图上的 iPhone SE)

我的代码:

struct ContentView: View {
    var body: some View {
        VStack(spacing: 0) {
            VStack(spacing: 0) {
                Rectangle()
                    .foregroundColor(.red)
                    .frame(height: 100)
                Spacer()
                    .frame(minHeight: 10, maxHeight: 100)
                Rectangle()
                    .foregroundColor(.green)
                    .frame(height: 100)
                Spacer()
                    .frame(minHeight: 10, maxHeight: 100)
                Rectangle()
                    .foregroundColor(.blue)
                    .frame(height: 100)
            }
            Spacer()
                .frame(minHeight: 10, maxHeight: 600)
            Rectangle() // keyboard
                .frame(height: 200)
        }
    }
}

所以问题是: maxHeight: 100 的垫片在 iPhone 11 Pro Max 上的高度 = 10(不是 100)。 (但是黑色视图和 VStack 之间的空间允许它)

如何做出我解释的行为?

【问题讨论】:

    标签: ios swift layout constraints swiftui


    【解决方案1】:

    您需要将idealHeight.fixedSize 修饰符一起用于Spacers:

    Spacer()
        .frame(minHeight: 10, idealHeight: 100, maxHeight: 600)
        .fixedSize()
    

    【讨论】:

      【解决方案2】:

      使用 Spacer(minLength: 10) 作为最后一个间隔。

      struct ContentView: View {
          var body: some View {
              VStack(spacing: 0) {
                  VStack(spacing: 0) {
                      Rectangle()
                          .foregroundColor(.red)
                          .frame(height: 100)
                      Spacer()
                          .frame(minHeight: 10, maxHeight: 100)
                      Rectangle()
                          .foregroundColor(.green)
                          .frame(height: 100)
                      Spacer()
                          .frame(minHeight: 10, maxHeight: 100)
                      Rectangle()
                          .foregroundColor(.blue)
                          .frame(height: 100)
                  }
                  Spacer(minLength: 10)
                  Rectangle() // keyboard
                      .frame(height: 200)
              }
          }
      }
      

      您的代码中的问题是,当您将 Spacer 包装在像 Spacer().frame(minHeight: 10, maxHeight: 600) 这样的框架内时,它首先被视为一个框架,然后是该框架内的一个 Spacer。并且框架具有与其他视图相同的默认布局优先级。所以父级会建议它与内部 VStack 相同的空间量。通过移除框架修饰符,Spacer 的布局优先级最低,因此内部 VStack 将占用尽可能多的空间,除了 spacer 要求的最少 10 个点和矩形要求的 200 个点。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-06-13
        • 2023-03-14
        • 2020-01-01
        • 2021-05-16
        • 2023-02-23
        • 2017-07-22
        • 2017-03-24
        相关资源
        最近更新 更多