Is it possible to extract the toolbar content in a separate var like using @ViewBuilder
?
I would like to extract it and set .toolBar(content: myToolBarContent)
var body: some View {
NavigationView {
List {
}
.toolbar(content: {
ToolbarItem(placement: .principal) {
Text("Hi")
}
ToolbarItem(placement: .navigationBarTrailing) {
Text("Ho")
}
})
}
}
You don't actually need to create another struct - instead you can use @ToolbarContentBuilder
. It's a @ViewBuilder
equivalent for ToolbarContent
:
struct ContentView: View {
var body: some View {
NavigationView {
List {}
.toolbar(content: myToolBarContent)
}
}
@ToolbarContentBuilder
func myToolBarContent() -> some ToolbarContent {
ToolbarItem(placement: .principal) {
Text("Hi")
}
ToolbarItem(placement: .navigationBarTrailing) {
Text("Ho")
}
}
}
If you want to separate the toolbar from the body, then you need to create a separate struct for Toolbar content. Here is a possible demo.
struct ContentView: View {
var body: some View {
NavigationView {
List {
}
.toolbar{MyToolBarContent()}
}
}
struct MyToolBarContent: ToolbarContent {
var body: some ToolbarContent {
ToolbarItem(placement: .principal) {
Text("Hi")
}
ToolbarItem(placement: .navigationBarTrailing) {
Text("Ho")
}
}
}
}
Worth adding on to pawello2222 answer by mentioning that on macOS, it doesn't take much more to enable nifty user customisable toolbars, e.g.
@main
struct myHappyAppyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
.commands {
ToolbarCommands() //<- Turns on the toolbar customization
}
}
}
struct ContentView: View {
var body: some View {
NavigationView {
List {}
.toolbar(id: "hihobar", content: myToolBarContent)
}
}
@ToolbarContentBuilder
func myToolBarContent() -> some CustomizableToolbarContent {
ToolbarItem(id: "hitag") {
Text("Hi")
}
ToolbarItem(id: "hotag") {
Text("Ho")
}
ToolbarItem(id: "spacertag") {
Spacer()
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With