SwiftUI main list scrollable header view without sections?

Viewed 7319

Is there a way to put a view in the list header without sections? The table views normally have a property called tableHeaderView which is a header for the whole table and has nothing to do with section headers.

I'm trying to have a list and be able to scroll it like tableHeaderView from UITableView.

struct MyView: View {
    
    let myList: [String] = ["1", "2", "3"]
    
    var body: some View {
        VStack {
            MyHeader()
            List(myList, id: \.self) { element in
                Text(element)
            }
        }
    }
}
2 Answers

Thanks to Asperi. This is my final solution for the table header.

struct MyHeader: View {
    var body: some View {
        Text("Header")
    }
}

struct DemoTableHeader: View {
    let myList: [String] = ["1", "2", "3"]

    var body: some View {
        List {
            MyHeader()
            ForEach(myList, id: \.self) { element in
                Text(element)
            }
        }
    }
}

Here is a simple demo of possible approach, everything else (like style, sizes, alignments, backgrounds) is extendable & configurable.

Tested with Xcode 11.4 / iOS 13.4

struct MyHeader: View {
    var body: some View {
        Text("Header")
            .padding()
            .frame(maxWidth: .infinity)
    }
}

struct DemoTableHeader: View {
    let myList: [String] = ["1", "2", "3"]

    let headerHeight = CGFloat(24)

    var body: some View {
        ZStack(alignment: .topLeading) {
            MyHeader().zIndex(1)               // << header
                .frame(height: headerHeight)

            List {
                Color.clear                    // << under-header placeholder
                    .frame(height: headerHeight)

                ForEach(myList, id: \.self) { element in
                    Text(element)
                }
            }
        }
    }
}
Related