简体   繁体   中英

How to make `VStack` view inside `ScrollView` expand up and take the space under navigation title while keeping the content in the same spot?

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:
在此处输入图像描述

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.

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 !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM