自定义 NavigationLink SwiftUI

Custom NavigationLink SwiftUI

我在 SwiftUI 中有一个自定义 NavigationLink。现在我正在尝试将 isActive 添加到我的 customNavLink,但我在所有项目中都面临着 Missing argument for parameter 'isActive' in call。我想让这个 isActive optional 在我需要的地方使用它。

你知道我该如何解决这个问题吗?

这是我的 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
            })
    }
}

如果您希望 isActive 成为 Optional,您必须在初始化程序和属性中声明它。然后,您将有条件地显示不同的 NavigationLink 初始值设定项,具体取决于您是否有 isActive Binding 来传递它:

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
                })
        }
    }
}