SwiftUI:通过百分比高度调整VStack的框架大小

11

我有一个卡片视图,我给了它一些大小。我知道这是错误的。我想要可调整大小并按百分比分割,例如blue = 70%red = 30%或类似的东西。但是不知道如何做。我是SwiftUI上的新手。下面是我的代码:

let screen = UIScreen.main.bounds

struct CardView: View {
  var body: some View {
    VStack {
      VStack {
        Text("Blue")
      }
      .frame(width: screen.width - 60, height: 180)
      .background(Color.blue)
      VStack {
        Text("Red")
      }
      .frame(width: screen.width - 60, height: 100)
      .background(Color.red)
    }
    .frame(width: screen.width - 60, height: 280)
  }
}

我的观点是:

输入图像描述

1个回答

17

这里是一个可计算的相对布局解决方案,基于GeometryReader注意:在这种情况下使用NSScreen是不合适的,因为可能导致不同型号上的预期布局

已在Xcode 12b中测试

demo

struct CardView: View {
    var body: some View {
        GeometryReader { gp in
            VStack {
                VStack {
                    Text("Blue")
                }
                .frame(width: gp.size.width, height: gp.size.height * 0.7)
                .background(Color.blue)
                VStack {
                    Text("Red")
                }
                .frame(width: gp.size.width, height: gp.size.height * 0.3)
                .background(Color.red)
            }
        }
        .frame(height: 280).frame(maxWidth: .infinity)
        .cornerRadius(24).padding(.horizontal, 30)
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接