11

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 2

14

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)
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

7

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)
                }
            }
        }
    }
}

3 Comments

Nice! But I wanted the header to also scroll with the list as well?
Then I misunderstood you - just remove placeholder and move header into List above ForEach.
Asperi, Yay Awesome! That worked. I posted my answer based on your comment here :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.