Trailing closure passed to parameter of type 'Visibility' that does not accept a closure

Hi All, I’m quite new to swift and am wondering why I am receiving a "Trailing closure passed to parameter of type 'Visibility' that does not accept a closure" error on the .toolbar { line?

I Have Supplied My Code Below.

Thanks in Advance,

Josh

//
//  HomeView.swift
//  Light
//
//  Created by Joshua Wolfson on 26/1/2023.
//

import SwiftUI

struct HomeView: View {
    var body: some View {
       
        Text("Home")
            .toolbar {
                
                ToolbarItem(placement: .navigationBarLeading)
                Button(action: NavigationLink(destination: AccountView()), label: Image(systemName: "gearshape"))
                
                ToolbarItem(placement: .principal) { Text("Welcome").font(.title)
                }
                ToolbarItem(placement: .navigationBarTrailing)
                Button(action: NavigationLink(destination: AccountView()), label: Image(systemName: "person.circle"))
                
            }
            .navigationBarTitleDisplayMode(.inline)
    }
}

struct HomeView_Previews: PreviewProvider {
    static var previews: some View {
        HomeView()
    }
}

You cannot place a NavigationLink inside a Button action code.

You can use a NavigationLink in it’s own right though.

In order to see the Navigation Bar at the top and the “buttons’” you want to use to navigate, then you need to wrap the Text() View in a NavigationStack as per the code below.
Also if you want a title to appear at the top in the middle on the navigation bar then you should use the modifier .navigationTitle("Welcome") rather than using a ToolBarItem as a defacto title :

struct HomeView: View {

    var body: some View {
        NavigationStack {
            Text("Home")
                .toolbar {
                    ToolbarItem(placement: .navigationBarLeading) {
                        NavigationLink(destination: AccountView()) {
                            Image(systemName: "gearshape")
                        }
                    }

//                    ToolbarItem(placement: .principal) { Text("Welcome").font(.title) }

                    ToolbarItem(placement: .navigationBarTrailing) {
                        NavigationLink(destination: AccountView()) {
                            Image(systemName: "person.circle")
                        }
                    }
                }
                .navigationTitle("Welcome")
                .navigationBarTitleDisplayMode(.inline)
        }
    }
}
1 Like