So I was working on a project and whenever I make a ZStack to get a background color, the subsequent VStack is basically somehow attached to the ZStack. I thought ZStack were similar to objects being stacked on top of each other.
However, the closer I make the bottomHeightMultiplier var closer to 100% the more the Text in the Vstack gets pushed off the screen. I was just trying to create a background view with the top 20% of any device screen being white and the bottom 80% of the screen being green.
Unfortunately the Text("Enter bill total") just ends up getting pushed off the screen. If I put the Spacer() below the Text, it gets pushed to the top and beyond the safe area. Putting it above the Text pushes it to bottom and beyond the safe area.
import SwiftUI
struct CalculatorScreen: View {
var screenWidth = UIScreen.main.bounds.width
var screenHeight = UIScreen.main.bounds.height
var topHeightMultiplier: CGFloat = 0.20
var bottomHeightMultiplier: CGFloat = 0.80
var body: some View {
ZStack {
VStack {
Color.white
.frame(minHeight: screenHeight*topHeightMultiplier)
Color.green
.frame(minHeight: screenHeight*bottomHeightMultiplier)
}
VStack {
Spacer()
Text("Enter bill total")
.foregroundColor(.black)
}
}
}
}
CodePudding user response:
This will do the trick. What really is happening is that when using UIScreen.bounds
, the safe areas create a problem, making the view longer than the screen long is. That means that the inner VStack pushes on the outer ZStack and thus makes the ZStack also longer than the device is. Thus, no the objects within the ZStack are completely independent, however the size of the parent changes when that of a child changes, implicitly affecting other child objects in the ZStack. The second VStack will be as long as the ZStack due to the Spacer(), making it look like it has been pushed off the screen.
Additionally, the VStack for the colors had a standard padding (now added spacing: 0
), creating a white line between the colors, eating up space as well which is not taken into account when calculating the height of the colors. My tip is to always use colors you can see when building blocks, that way you immediately spot safe area issues and unwanted paddings.
struct CalculatorScreen: View {
var topHeightMultiplier: CGFloat = 0.20
var bottomHeightMultiplier: CGFloat = 0.80
var body: some View {
GeometryReader { geometry in
ZStack {
VStack(spacing: 0) {
Color.purple
.frame(minHeight: geometry.size.height*topHeightMultiplier)
Color.green
.frame(minHeight: geometry.size.height*bottomHeightMultiplier)
}
.ignoresSafeArea()
VStack {
Spacer()
Text("Enter bill total")
.foregroundColor(.black)
}
}
}
}
}