Search code examples
iosswiftiphoneipadswiftui

SwiftUI Layout - NavigationView in VStack - fill height


Given the following view:

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            SomeView()
            Spacer()

            HStack {
                Text("Some Text1")
                Spacer()
                Text("Some Text2")
                Spacer()
                Text("Some Text2")
            } .background(Color.green)

        } .background(Color.blue)

    }
}

struct SomeView: View {
    var body: some View {
        VStack {
            Text("Hello, World!")
        } 
    }
}

enter image description here

Everything works as expected. The green HStack is at the bottom of the screen, the rest of the screen area is filled blue by the remaining VStack content.

As soon as SomeView get wrapped by a NavigationView this behavior changes. The green HStack is still at the bottom of the screen but the NavigationView doesn't fill the entire rest. There is a small blue are left. How can this be removed to let the NavigationView fill the content area?

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            SomeView()
            Spacer()

            HStack {
                Text("Some Text1")
                Spacer()
                Text("Some Text2")
                Spacer()
                Text("Some Text2")
            } .background(Color.green)

        } .background(Color.blue)

    }
}

struct SomeView: View {
    var body: some View {
        NavigationView {
            VStack {
                Text("Hello, World!")
            } .navigationBarTitle(Text("Test"))
        }
    }
}

enter image description here

Thanks for any help in advance!


Solution

  • Delete Spacer and set VStack spacing to zero. Here is my code. I hope it will help you.

        struct ContentView: View {
            var body: some View {
                VStack(spacing: 0) {
                    SomeView()
                    HStack {
                        Text("Some Text1")
                        Spacer()
                        Text("Some Text2")
                        Spacer()
                        Text("Some Text2")
                    } .background(Color.red)
    
                } .background(Color.blue)
    
            }
        }
    
        struct SomeView: View {
            var body: some View {
                NavigationView {
                    VStack {
                        Text("Hello, World!")
                    } .navigationBarTitle(Text("Test"))
                }
            }
        }