Unknown white space inside SwiftUI which can't display any element on top of it

Viewed 49

There is a white space inside my SwiftUI View which is not filled out properly. In that white space area, there is nothing that I can display on top of it. I tried putting a red border around each element one by one, and I found out that the white space belongs to ZStack.

However, I still could not get rid of it. How to deal with this problem?

Below are my code and reference picture:

unknown white space image

struct ForTest: View {
var body: some View {
    ZStack {
        Color.gray.edgesIgnoringSafeArea(.all)
        VStack {
            ZStack(alignment: .topLeading) {
                Rectangle()
                    .fill(.red)
                    .frame(width: .infinity, height: 300)
                    .edgesIgnoringSafeArea(.all)
                    .background(.white)
            }
            .border(.red)
            
            ScrollView {
                VStack {
                    ForEach(1...15, id: \.self) {_ in
                        Text("Hello, World")
                            .padding()
                    }
                }
            }
        }
    }
}
}
2 Answers

try putting .frame(height: 300) after the .background(.white), and of course remove .frame(width: .infinity, height: 300)

First of all, there are a lot of things to remove.

  • You might need to get rid of the border on the ZStack.
  • background modifier from the Rectangle.
  • Also you have to fix the frame modifier on the rectangle. You need to remote .infinity from the width as said in the response https://stackoverflow.com/a/72581341/17708926. You need to replace it with maxWidth and maxWidth arguments. then set both to .infinity. This will fix the problem.

fixed screenshot

Related