Search code examples
swiftswiftuivstackios-navigationviewswiftui-navigationview

Double List in NavigationView [Swift]


I'm trying to fit two categories of an item on two different list, named 'Wide-Field' and 'Deep-Sky', however I want the second list to be below the first.

I was expecting it to look something like this:

enter image description here

However, instead it splits the screen in half and I get this result:

enter image description here

My current code:

import SwiftUI

struct ListView: View {
    @Environment(\.colorScheme) var colorScheme

    var body: some View {
        NavigationView {
            VStack {
                List {
                    ForEach(Photographs.wideFieldPhotos, id: \.self) { key in
                        HStack {
                            PhotographRow(photo: key)
                        }
                    }
                }
                .navigationBarTitle("Wide-Field")
                List {
                    ForEach(Photographs.deepSkyPhotos, id: \.self) { key in
                        HStack {
                            PhotographRow(photo: key)
                        }
                    }
                }
                .navigationBarTitle("Deep-Sky")
            }
        }
    }
}

struct ListView_Previews: PreviewProvider {
    static var previews: some View {
        ListView()
    }
}

Solution

  • I assume you want instead one List with two Sections, like

    var body: some View {
        NavigationView {
            List {
                Section(header: Text("Wide-Field").font(.largeTitle)) {
                    ForEach(Photographs.wideFieldPhotos, id: \.self) { key in
                        HStack {
                            PhotographRow(photo: key)
                        }
                    }
                }
    
                Section(header: Text("Deep-Sky").font(.largeTitle)) {
                    ForEach(Photographs.deepSkyPhotos, id: \.self) { key in
                        HStack {
                            PhotographRow(photo: key)
                        }
                    }
                }
            }
        }
    }