具有多个 NavigationLink 的自定义按钮

Custom Button with Multiple NavigationLink

我希望能够在多个地方使用我的自定义按钮。现在它只能在点击时导航到 StartWithPhoneView。当我在其他地方使用时,我也想导航到另一个视图。我可以通过创建两个自定义按钮来实现,但它是代码重复。

struct CustomButtonView: View {
@State var isTapped: Bool = false
var text = ""
var body: some View {
    Button(action: {
        print("Create account tapped")
        self.isTapped.toggle()
    }, label: {
        RoundedRectangle(cornerRadius: 5)
            .frame(width: UIScreen.main.bounds.width / 1.205, height: 44)
            .foregroundColor(.blue)
            .overlay(Text(text))
            .foregroundColor(.white)
    })
    .padding(.top,15)
    NavigationLink("", destination: StartWithPhoneView(), isActive: $isTapped)
}

}

我在此 SignUpView 中使用自定义按钮

struct SignupView: View {
var body: some View {
    NavigationView {
        VStack {
            CustomButtonView(text: "Create an account" )
        }
        NavigationLink("", destination: StartWithPhoneView(), isActive: CustomButtonView.$isTapped) // I want to reach inside CustomButtonView to fetch isTapped
    }
}

}

您可以使用Generic类型这是一个视图

  struct CustomButtonView<Destination: View>: View { //<-here
    @State var isTapped: Bool = false
    var destination: Destination //<- here
    var text = ""
    var body: some View {
        Button(action: {
            print("Create account tapped")
            self.isTapped.toggle()
        }, label: {
            RoundedRectangle(cornerRadius: 5)
                .frame(width: UIScreen.main.bounds.width / 1.205, height: 44)
                .foregroundColor(.blue)
                .overlay(Text(text))
                .foregroundColor(.white)
        })
        .padding(.top,15)
        NavigationLink("bbbbb", destination: destination, isActive: $isTapped) //<- here
    }
}