【问题标题】:Custom Button with Multiple NavigationLink具有多个 NavigationLink 的自定义按钮
【发布时间】:2021-02-11 12:13:26
【问题描述】:

我希望能够在多个地方使用我的自定义按钮。现在它只能在点击时导航到 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
    }
}

}

【问题讨论】:

    标签: button swiftui navigation


    【解决方案1】:

    你可以使用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
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-20
      • 2017-10-11
      • 1970-01-01
      相关资源
      最近更新 更多