I am working on a SwiftUI project, and I am trying to have multiple different Toolbar versions in my app. When one button is pressed, they ideally should change. So, I have defined a few different Toolbars using this definition (the actual code in the toolbars is not important):
@ToolbarContentBuilder fileprivate var ______: some ToolbarContent {
ToolbarItem(...)
ToolbarItem(...)
}
My next step is to create a @State variable that holds the currently selected toolbar. I tried to do this:
@State var navBarView: some ToolbarContent = _________
However, this gave the error:
Result builder attribute 'ToolbarContentBuilder' can only be applied to a property if it defines a getter
Does anyone know how to complete this goal or get around this error? Thanks!
>Solution :
You should not use ToolbarContent as a @State, in the same way that you should have a View as a @State.
Create an enum that encodes the many toolbars that you have, e.g.
enum ToolbarState {
case one, two
@ToolbarContentBuilder
var content: some ToolbarContent {
switch self {
case .one:
ToolbarItem {
Button("Foo1") {
}
}
ToolbarItem {
Button("Foo2") {
}
}
case .two:
ToolbarItem {
Button("Bar") {
}
}
}
}
}
Use this as the state:
@State var toolbarState = ToolbarState.one
var body: some View {
NavigationStack {
Button("Change State") {
toolbarState = .two
}.toolbar {
toolbarState.content
}
}
}