How to create a custom toolbar?

418 Views Asked by At

I want to have a sticky toolbar that has multiple different filtering options above a List in SwiftUI. Is there a way to just place a full custom view inside the .toolbar property of a List?

With the below code, things look very unexpected

var body: some View {
    NavigationView {
        List() {
            Text("List item")
        }
        .toolbar {
            ToolbarItem(placement: .navigationBarLeading) {
                VStack {
                    Toggle(isOn: $viewModel.isPound) {
                        Text("test")
                    }
                    .toggleStyle(.switch)
                    Text("A slider to control data")
                    Text("Another filtering option")
                    Text("Some random piece of information")
                }
            }
        }
    }
}

SwiftUI List Toolbar

SwiftUI List Toolbar Scrolled

1

There are 1 best solutions below

1
On BEST ANSWER

The NavigationBar is a fixed height for iOS, and is really designed for buttons. You can see the problem (and the space you have to work with) if you add a background colour to it.

struct ContentView: View {
    
    @State private var isPound = false
    
    var body: some View {
        NavigationView {
            List() {
                Text("List item")
            }
            .toolbar {
                ToolbarItem(placement: .navigationBarLeading) {
                    VStack {
                        Toggle(isOn: $isPound) {
                            Text("test")
                        }
                        .toggleStyle(.switch)
                        Text("A slider to control data")
                        Text("Another filtering option")
                        Text("Some random piece of information")
                    }
                    .border(.red)
                }
            }
            .toolbarBackground(.visible, for: .navigationBar)
            .toolbarBackground(.red, for: .navigationBar)
        }
    }
}

enter image description here