swiftswiftuitoolbaritems

How can I push a view from a ToolbarItem?


ToolbarItem(placement: .bottomBar) {
    NavigationLink(
        destination: NoteView(note: Note())
    ) {
        Image(systemName: "square.and.pencil")
    }
}

This code is not working as expected: no action is being performed when I tap on the image.

Any idea why or way around?


Solution

  • A possible workaround is to move the NavigationLink outside the toolbar and activate with the isActive parameter:

    struct ContentView: View {
        @State var linkActive = false
    
        var body: some View {
            NavigationView {
                Text("Test")
                    .background(
                        NavigationLink(destination: Text("Destination"), isActive: $linkActive) {}
                    )
                    .toolbar {
                        ToolbarItem(placement: .bottomBar) {
                            Button(action: {
                                linkActive = true
                            }) {
                                Image(systemName: "square.and.pencil")
                            }
                        }
                    }
            }
        }
    }