Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Making a State variable of ToolbarContent SwiftUI

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
        }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading