SwiftUI 按高度百分比调整 VStack 的帧大小

atu*_*n23 3 swift swiftui

我有一个卡片视图。我给自己的尺寸。我知道这是错误的。我想调整大小并除以像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)
  }
}

Run Code Online (Sandbox Code Playgroud)

而我的观点是:

在此处输入图片说明

Asp*_*eri 7

这是基于的可计算的相对布局解决方案GeometryReader注意:在这种情况下使用 NSScreen 是不合适的,因为它可能会在不同模型上引入预期的布局

使用 Xcode 12b 测试

演示

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)
    }
}
Run Code Online (Sandbox Code Playgroud)