UPDATE #2:
Thanks to this answer and code from @kontiki, here's what easily works instead of using this deprecated method:
Declare this:
@State private var rect: CGRect = CGRect()
Then create this:
struct GeometryGetter: View {
@Binding var rect: CGRect
var body: some View {
GeometryReader { geometry in
Group { () -> ShapeView<Rectangle, Color> in
DispatchQueue.main.async {
self.rect = geometry.frame(in: .global)
}
return Rectangle().fill(Color.clear)
}
}
}
}
(For those familiar with UIKit
, you are basically creating an invisible CALayer
or UIView
in the parent and passing it's frame to the subview - apologies for not being 100% technically accurate, but remember, this is not a UIKit
stack in any way.)
Now that you have the parent frame, you can use it as a base for a percentage - or "relative" - of it. In this question there's a nested VStack
inside another and you want the lower Text
to be twice the vertical size of the top one. In the case of this answer, adjust your `ContentView to this:
struct ContentView : View {
@State private var rect: CGRect = CGRect()
var body: some View {
VStack (spacing: 0) {
RedView().background(Color.red)
.frame(height: rect.height * 0.25)
YellowView()
}
.background(GeometryGetter(rect: $rect))
}
}
UPDATE #1:
As of beta 4, this method is deprecated. relativeHeight
, relativeWidth
, relativeSizehave all been deprecated. Use
frameinstead. If you want *relatve* sizing based on a
View's parent, use
GeometryReader` instead. (See this question.)
ORIGINAL POST:
Here's what you want. Keep in mind that without modifiers, everything is centered. Also, relativeHeight
seems (at least to some) not very intuitive. The key is to remember that in a VSTack
the parent is 50% of the screen, so 50% of 50% is actually 25%.
Alternatively, you can dictate frame
heights (letting the width take up the whole screen). but your example suggests you want the red view to be 25% of the entire screen no matter what the actual screen size is.
struct RedView: View {
var body: some View {
ZStack {
Color.red
Text("Subview A")
}
}
}
struct YellowView: View {
var body: some View {
ZStack {
Color.yellow
Text("Subview B")
}
}
}
struct ContentView : View {
var body: some View {
VStack (spacing: 0) {
RedView().background(Color.red).relativeHeight(0.50)
YellowView()
}
}
}
