Search code examples
swiftuiswiftui-navigationlink

Custom NavigationLink SwiftUI


I have a custom NavigationLink in SwiftUI. Now I'm trying to add isActive to my customNavLink but I'm facing with Missing argument for parameter 'isActive' in call across all project. I want to make this isActive optional to use where I need it.

Do you know how could I resolve this issue?

This is My CustomNavLink

struct CusNavLink<Label: View, Destination: View>: View {

    let destination: Destination
    let label : Label
    let isActive: Binding<Bool>

    init(destination: Destination, isActive: Binding<Bool>, @ViewBuilder label: () -> Label) {
        self.destination = destination
        self.label = label()
        self.isActive = isActive
    }

    var body: some View {
        NavigationLink(
            destination: CusNavContainer{
                destination
            }
                .navigationBarHidden(true),
            isActive: isActive,
            label:{
                label
            })
    }
}

Solution

  • If you want isActive to be Optional, you'd have to declare it as such in the initializer and properties. Then, you'd conditionally display a different NavigationLink initializer depending on if you have an isActive Binding to pass it:

    struct CusNavLink<Label: View, Destination: View>: View {
    
        let destination: Destination
        let label : Label
        let isActive: Binding<Bool>?
    
        init(destination: Destination, isActive: Binding<Bool>? = nil, @ViewBuilder label: () -> Label) {
            self.destination = destination
            self.label = label()
            self.isActive = isActive
        }
    
        var body: some View {
            if let isActive = isActive {
                NavigationLink(
                    destination: CusNavContainer {
                        destination
                    }
                    .navigationBarHidden(true),
                    isActive: isActive,
                    label:{
                        label
                    })
            } else {
                NavigationLink(
                    destination: CusNavContainer {
                        destination
                    }
                    .navigationBarHidden(true),
                    label:{
                        label
                    })
            }
        }
    }