Maklaus
Maklaus

Reputation: 688

How to make two Lists in one View scroll as one page in SwiftUI?

I'm trying to add two tables with different sizes to one view in SwiftUI. I want both tables be fully expanded and the whole view to scroll as one. For now I only get both tables fixed size and scroll separately.

some View {
    VStack {
        Text("Table foo")
        List(foo { item in Text(item.name) })

        Text("Table bar")
        List(bar { item in Text(item.name) })
    }
}

Tried changing VStack to a ScrollView, it makes things even worse - tables are becoming one liners.

Also tried replacing List() with ForEach() but then I lose features of the List() I actually want.

Upvotes: 8

Views: 7235

Answers (2)

hengyu
hengyu

Reputation: 76

You can use Form to embed two lists in a scroll view.

Reference: https://developer.apple.com/documentation/swiftui/form .

Upvotes: 1

Chuck H
Chuck H

Reputation: 8276

I think you want one List with multiple ForEach's. Optionally, you could make it a grouped List with multiple sections. Adapted for your sample, the following concept has worked well for me on several occasions:

struct SwiftUIView: View {
    var body: some View {
        List {
            Section(header: Text("Table foo"))
            {
                ForEach(foo) { item in Text(item.name) }
            }
            Section(header: Text("Table bar"))
            {
                ForEach(bar) { item in Text(item.name) }
            }
        }
        .listStyle(GroupedListStyle())
    }
}

Upvotes: 12

Related Questions