Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI Adjusting frame size of VStacks by percent height

Tags:

swift

swiftui

I have a card view. Which sizes I give myself. I know that is wrong. I want to do it resizable and divided by percent like blue = 70% & red = 30% or something like this. But don't know how. Im new on SwiftUI. There is my code below:

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)
  }
}

And my view is:

enter image description here

like image 438
aturan23 Avatar asked Jun 29 '20 15:06

aturan23


Video Answer


1 Answers

Here is calculable relative layout solution based on GeometryReader (Note: using NSScreen is inappropriate in such case as might introduce expected layout on different models)

Tested with 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)
    }
}
like image 69
Asperi Avatar answered Nov 15 '22 12:11

Asperi