0

Here is an example of what i currenly have:

struct ContentView: View {
    var body: some View {
        NavigationView {
            ScrollView {
                VStack() {
                    Text("Foo")
                }
                .frame(maxWidth: .infinity, idealHeight: 200)
                .background(Color(uiColor: .systemBackground))
            }
            .background(Color(uiColor: .secondarySystemBackground))
            
            .navigationTitle("Title")
        }
    }
}

Here is what it renders:
enter image description here

What i want to achieve is the white background all the way up to the top of the screen while preserving the padding so that the actual content of the VStack is displayed below the title and not underneath it and when scroll happens VStack's content follows the title when it goes from large to inline.

ansavchenco
  • 535
  • 6
  • 14

1 Answers1

0

Alright, i found a way to do that. It's hacky and most probably won't work properly for all screen sizes or when changing orientation of the device but i recon it would work for most iPhone models in portrait mode.

The idea is to place a ZStack inside ScrollView and put my VStack there along with a Rectangle of required color and then offset the Rectangle up to occupy the space underneath the navigation bar and more to keep the color the same when scroll spring effect happens.

Here it the code:

struct ContentView: View {
    var body: some View {
        NavigationView {
            ScrollView {
                ZStack(alignment: .top) {
                    Rectangle()
                        .foregroundColor(Color(uiColor: .systemBackground))
                        .frame(height: UIScreen.main.bounds.height * 0.5)
                        .offset(y: -UIScreen.main.bounds.height * 0.5)
                        .padding(.bottom, -UIScreen.main.bounds.height * 0.5)
                        
                    
                    VStack() {
                        Text("Foo")
                    }
                    .frame(maxWidth: .infinity)
                    .frame(height: 200)
                    .background(Color(uiColor: .systemBackground))
                    
                }
            }
            .background(Color(uiColor: .secondarySystemBackground))
            
            .navigationTitle("Title")
        }
    }
}

Note: don't forget to set alignment: .top to ZStack!

ansavchenco
  • 535
  • 6
  • 14